我正在尋找最好的方式,以功能與包含與函數的輸入多個項目的字典結合如何用包含比函數具有參數更多項目的字典調用函數?
基本** 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'
經過一番研究,我想出了以下方法:
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 = {'a':1,
'b':2,
'c':3}
print combine(foo,d)
--> 3
我的問題是:這是處理這個問題的一個很好的方式,或者是有一個更好的做法還是有mechan我可能錯過了這種語言嗎?
感謝。我應該提到,也許我正在爲一個程序構建一個框架,其他人(有時候是python的相對新手)正在創建這些功能。因此,我寧願他們不必處理** kwargs,而是使用基本函數輸入:foo(a,b);我想在實用函數中隱藏這個** kwargs過濾複雜性。 –