Unpacking keyword arguments, but only the ones that match the function

前端 未结 3 720
执念已碎
执念已碎 2020-12-17 09:07

Let\'s say I have a function:

def foo(a=None, b=None, c=None):
  return \"a:%s, b:%s, c:%s\" % (a, b, c)

I have a dictionary with some (or

3条回答
  •  暖寄归人
    2020-12-17 09:49

    @Ashwini Chaudhary has a very pythonic way of solving your problem. However, it requires changing the signature of your foo function.

    If you don't want to change your function signature, you can use introspection to find out what arguments your function expects:

    arg_count = foo.func_code.co_argcount
    args = foo.func_code.co_varnames[:arg_count]
    
    args_dict = {}
    for k, v in d.iteritems():
        if k in args:
            args_dict[k] = v
    
    foo(**args_dict)
    

提交回复
热议问题