我正在寻找将函数与包含比函数输入更多项的字典组合在一起的最佳方法
在这种情况下,基本**kwarg拆包失败:
def foo(a,b):
return a + b
d = {'a':1,
'b':2,
'c':3}
foo(**d)
--> TypeError: foo() got an unexpected keyword argument 'c'
Run Code Online (Sandbox Code Playgroud)
经过一些研究,我想出了以下方法:
import inspect
# utilities
def get_input_names(function):
'''get arguments names from function'''
return inspect.getargspec(function)[0]
def filter_dict(dict_,keys):
return {k:dict_[k] for k in keys}
def combine(function,dict_):
'''combine a function with a dictionary that may contain more items than the function's inputs '''
filtered_dict = filter_dict(dict_,get_input_names(function))
return function(**filtered_dict)
# examples
def foo(a,b):
return a + b
d = …Run Code Online (Sandbox Code Playgroud)