Python: dynamically create function at runtime Python: dynamically create function at runtime python python

Python: dynamically create function at runtime


Use exec:

>>> exec("""def a(x):...   return x+1""")>>> a(2)3


Did you see this, its an example which tells you how to use types.FunctionType

Example:

import typesdef create_function(name, args):    def y(): pass    y_code = types.CodeType(args,                            y.func_code.co_nlocals,                            y.func_code.co_stacksize,                            y.func_code.co_flags,                            y.func_code.co_code,                            y.func_code.co_consts,                            y.func_code.co_names,                            y.func_code.co_varnames,                            y.func_code.co_filename,                            name,                            y.func_code.co_firstlineno,                            y.func_code.co_lnotab)    return types.FunctionType(y_code, y.func_globals, name)myfunc = create_function('myfunc', 3)print repr(myfunc)print myfunc.func_nameprint myfunc.func_code.co_argcountmyfunc(1,2,3,4)# TypeError: myfunc() takes exactly 3 arguments (4 given)


If you need to dynamically create a function from a certain template try this piece:

def create_a_function(*args, **kwargs):    def function_template(*args, **kwargs):        pass    return function_templatemy_new_function = create_a_function()

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.