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, ...
解决方案
Use exec:
>>> exec("""def a(x):
... return x+1""")
>>> a(2)
3