简体   繁体   English

Python:如何仅从字典将所需的参数传递给函数?

[英]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). 将会出现语法错误(因为b未在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 : 您可以使用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 . 给出11


Thanks Eugene, getargspec is legacy, instead you should use getfullargspec which has the same usage in this case. 感谢Eugene, getargspec是遗留的,相反,您应该使用在这种情况下具有相同用法的getfullargspec

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 : 这是获得字典并仅使用'b'键的函数示例:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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