How to dynamically create a function in Python?
I saw a few answers here but I couldn't find one which would describe the most general case.
Consider:
def a(x):
return x + 1
How to create such function on-the-fly? Do I have to compile('...', 'name', 'exec')
it? But what then? Creating a dummy function and replacing its code object for then one from the compile step?
Or should I use types.FunctionType
? How?
I would like to customize everything: number of argument, their content, code in function body, the result, ...
What about this approach?
In this example I'm parametrizing first order functions on one variable (x -> ax+b) in one class:
Here
u
will be the function x->2x+3.If you need to dynamically create a function from a certain template try this piece:
Within function create_a_function() you can control, which template to chose. The inner function function_template serves as template. The return value of the creator function is a function. After assignment you use my_new_function as a regular function.
Typically, this pattern is used for function decorators, but might by handy here, too.
You can use lambda for this.
Use
exec
:Did you see this, its an example which tells you how to use
types.FunctionType
Example: