Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to define functions dynamically in Python

Shulou Source: shulou.com Published: 2022-06-02 07:09:54 10月04日 Update

How to dynamically define functions in Python, I believe that many inexperienced people are helpless about this, so this article summarizes the causes and solutions of the problem, through this article I hope you can solve this problem.

Python operations: dynamically defining functions

Based on MIT License

In Python, there is no syntactic sugar that simplifies function definitions at runtime. However, this does not mean that it is impossible or difficult to achieve.

from types import FunctionType foo_code = compile('def foo(): return "bar"', "", "exec") foo_func = FunctionType(foo_code.co_consts[0], globals(), "foo") print(foo_func())

Output:

bar

analysis

Looking at the code line by line, you can see how fragile the language/interpreter barrier is.

>>> from types import FunctionType

Python documentation typically does not list characteristics that are not intended for manually created classes (which is perfectly reasonable). There are three ways to solve this problem: help(), inspect (unable to view built-in methods), and finally, look at the CPython source code.

In this case, both help() and inspect do the job, but a look at the actual source code reveals more details about the data types.

>>> from inspect import signature >>> signature(FunctionType)

1. code

Inside is a PyCodeobject, open to the outside as types.CodeType. Non-built-in methods have a__code__attribute that holds the corresponding code object. With the built-in compile() method, you can create types.CodeType objects at runtime.

2. globals

If a function references a variable that is not defined locally, but is passed in as a parameter, supplied by default parameter values, or supplied through a closure context, it is looked up in the globals dictionary.

The built-in globals() method returns a reference to the global symbol table of the current module and can therefore be used to provide a dictionary that always matches the state of the current table. Any other dictionary passed in is also allowed (FunctionType((lambda: bar).__ code__, {"bar" : "baz"}, "foo")() == "baz")。

3. name (optional)

Controls the__name__property of the returned function. Only really useful for lambdas (they usually don't have names due to anonymity), and rename functions.

4. argdefs (optional)

Provides a way to supply default parameter values (def foo(bar="baz")) by passing in a tuple containing an object of any type.(FunctionType((lambda bar: bar).__ code__, {}, "foo", (10,))() == 10)。

5. closure (optional)

(If you need CPython (PyPy, Jython,...) Python VM, probably shouldn't be touched because it depends heavily on implementation details).

A tuple of cell objects. Creating a cell object isn't entirely straightforward, as you need to call CPython's internals, but there's a library that makes it easier: exalt (shameless advertising). This library was developed by the author.

>>> foo_code = compile('def foo(): return "bar"', "", "exec")

Compile() is a built-in method, and therefore document-rich.

The exec pattern is used because defining a function requires multiple statements.

>>> foo_func = FunctionType(foo_code.co_consts[0], globals(), "foo")

Aggregates everything and assigns dynamically created functions to a variable.

The function compiled from the previous sentence becomes the first constant of the generated code object, so simply pointing to foo_code is not sufficient. This is a direct consequence of the exec pattern, because the generated code object can contain multiple constants.

>>> print(foo_func())

Dynamically generated functions can be called just like any other function.

After reading the above, do you know how to define functions dynamically in Python? If you still want to learn more skills or want to know more related content, welcome to pay attention to the industry information channel, thank you for reading!

Tags: Functions methods objects dynamics code content parameters dictionaries properties more problems generation variables multiple constants documents schemas source code types details Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Docker NVidia MySQL Xiaomi