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, ...
Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.
Add self. initialize() to myfunc() , this should do what you are looking for. class MyClass(object): def __init__(self): pass def initialize(self): print("I'm doing some initialization") def myfunc(self): self. initialize() print("This is myfunc()!")
Passing arguments to the dynamic function is straight forward. We simply can make solve_for() accept *args and **kwargs then pass that to func() . Of course, you will need to handle the arguments in the function that will be called.
1 Answer. You can use either vars() or globals() built-in method to generate dynamic variable names in python. I am generating variables x_0, x_1,...,x_4. I am generating variables y_0, y_1,...,y_4.
Use exec
:
>>> exec("""def a(x): ... return x+1""") >>> a(2) 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With