简体   繁体   中英

Python: How to only pass needed arguments into function from a dictionary?

Assume now I have a well-defined function

def f1(a):
    ...

and i can not change its definition. Now I want to call it with a argument from a dictionary

D={ 'a':1 , 'b':2}

If I call it like

f1(**D)

there will be a syntax error (because b is not defined in f1). My question is if I can find a smart way to let the function to find the argument it needed only?

You can use inspect.getargspec :

d = {'a': 5, 'b': 6, 'c': 7}
def f(a,b):
    return a + b

f(*[d[arg] for arg in inspect.getargspec(f).args])

which gives 11 .


Thanks Eugene, getargspec is legacy, instead you should use getfullargspec which has the same usage in this case.

You could get the argument names from the function's code object , then lookup the values for them in the dictionary:

>>> def f(a):
...     b = 2
...     return a + b
...
>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> nargs = f.__code__.co_argcount
>>> varnames = f.__code__.co_varnames
>>> f(*(D[arg] for arg in varnames[:nargs]))
3

Here is an example of function that got a dictionary and use only the 'b' key :

In [14]: def f1(mydict):
    ...:     return mydict['b']
    ...: 

In [15]: x={'a': 1, 'b':2}

In [16]: f1(x)
Out[16]: 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM