Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: dynamically create function at runtime

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, ...

like image 863
Ecir Hana Avatar asked Jul 02 '12 09:07

Ecir Hana


People also ask

How do you create a dynamic function in Python?

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.

How do you make a function run automatically in Python?

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()!")

How do you pass a parameter to a function dynamically in Python?

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.

How do you call a variable dynamically in Python?

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.


1 Answers

Use exec:

>>> exec("""def a(x): ...   return x+1""") >>> a(2) 3 
like image 126
mavroprovato Avatar answered Sep 22 '22 08:09

mavroprovato