Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically define the (keyword) arguments to a function?

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.

like image 262
Doctor J Avatar asked Sep 19 '25 14:09

Doctor J


1 Answers

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.

like image 187
Jau A Avatar answered Sep 22 '25 03:09

Jau A