Based on my interpretation of your requirements - you want to dynamically define a function with a signature that matches the contents of the dict
provided at runtime, there are two problems that make it impractical.
- If arguments are defined at runtime, how can your function refer to variables? Are you also planning to create a function body at runtime?
dict
are unordered, so you cannot reliably use them to determine positional arguments
I suspect this is an XY problem. If you can explain what you are trying to achieve, perhaps we can help.
However , provided you are trying to assign default keyword arguments using dict
, one way to achieve this would be to use decorators . For instance:
def defaultArgs(default_kw): "decorator to assign default kwargs" def wrap(f): def wrapped_f(**kwargs): kw = {} kw.update(default_kw)
You can then use this decorator to assign default keyword arguments to a function that expects only keyword arguments:
defaults = {'foo':0, 'bar':1, 'baz':2} @defaultArgs(defaults) def func(**kwargs): print kwargs
Results:
func()
Note that you cannot use positional arguments:
func(1, 2, 3)
source share