What I want to accomplish:
dct = {'foo':0, 'bar':1, 'baz':2}
def func(**dct):
pass
#function signature is now func(foo=0, bar=1, baz=2)
However, the ** syntax is obviously clashing here between expanding a dict (what I want to do) and declaring a parameter that holds the keyword arguments (what I don’t want to do).
Is this possible?
Based on my interpretation of your requirements — you want to dynamically define a function with a signature that matches the content of a
dictprovided at runtime — there are two issues here which makes it impractical.dicts are unordered, so you cannot reliably use them to define positional argumentsI suspect this is an XY problem. If you can explain what you’re trying to achieve then perhaps we can be of better help.
However, assuming you’re trying to assign default keyword arguments using a
dictthen one way to achieve this would be to use decorators. For example:You can then use this decorator to assign default keyword arguments to a function that expects only keyword arguments:
Results:
Note that you will not be able to use positional arguments: