Is it possible to define the keyword arguments to a function dynamically?
Normally you have something like this:
def f(a=None, b=None):
return locals()
What I want is to define a function with the keyword args from a dict; so this would give the same function as above:
dyn_args = {'a': None, 'b': None}
def f(?magic(dyn_args)?):
return locals()
The reason is I want the function to only accept kwargs that match the fields of a namedtuple, and error on anything else. The function should work with a few different namedtuples (and if they change), and I'd like to keep it DRY. I can work around it with kwargs and validation, but mostly I'm just curious -- dirty hacks welcome.
It seems fastcore's use_kwargs
decorator does just what you're asking for:
https://fastcore.fast.ai/meta.html#use_kwargs
To see how this is implemented, you can just have a look at its code in github:
https://github.com/fastai/fastcore/blob/master/fastcore/meta.py#L95
There is also a similar decorator, use_kwargs_dict
, which also indicates the default values to be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With