Just as a dynamic class can be created using type(name, base-classes, namespace-dict), can a dynamic function be created?
I’ve tried doing something along the lines of:
>>> f = type("f", (function,), {})
NameError: name 'function' is not defined
Ok, so I’ll be clever, but:
>>> def fn():
... pass
...
>>> type(fn)
<type 'function'>
>>> f = type("f", (type(fn),), {})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type 'function' is not an acceptable base type
Does Python specifically prevent the creation of dynamic functions in the same way it allows dynamic classes?
Edit: Note, I’d disallow any use of exec.. Since my question is does the Python language itself permit this.
Thanks in advance.
There is
types.FunctionTypewhich you can use to dynamically create a function e.g.Output:
You might object that this is not dynamic because I am using code from another function, but that was just an example there is a way to generate code from python strings e.g.
Output:
Now that is dynamic!
OP is worried about the dynamic nature of such function so here is another example
Output:
Note:
Creating Function object like this seems to have limitations e.g. it is not easy to pass arguments, because to pass arguments we need to pass correct co_argcount, co_varnames and other 12 variables to
types.CodeType, which theoretically can be done but will be error prone, an easier way is to import string as a module and you have a full fledged function e.g.Output: