小编Len*_*ken的帖子

如何使用包含比函数具有参数更多的项的字典来调用函数?

我正在寻找将函数与包含比函数输入更多项的字典组合在一起的最佳方法

在这种情况下,基本**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)

python dictionary named-parameters kwargs

26
推荐指数
4
解决办法
997
查看次数

标签 统计

dictionary ×1

kwargs ×1

named-parameters ×1

python ×1