Python 如何忽略传递给函数的意外关键字参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26515595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:35:08  来源:igfitidea点击:

How does one ignore unexpected keyword arguments passed to a function?

pythonfunctiondictionary

提问by rspencer

Suppose I have some function, f:

假设我有一些功能,f

def f (a=None):
    print a

Now, if I have a dictionary such as dct = {"a":"Foo"}, I may call f(**dct)and get the result Fooprinted.

现在,如果我有一个字典,例如dct = {"a":"Foo"},我可以调用f(**dct)Foo打印结果。

However, suppose I have a dictionary dct2 = {"a":"Foo", "b":"Bar"}. If I call f(**dct2)I get a

但是,假设我有一本字典dct2 = {"a":"Foo", "b":"Bar"}。如果我打电话给f(**dct2)

TypeError: f() got an unexpected keyword argument 'b'

Fair enough. However, is there anyway to, in the definition of for in the calling of it, tell Python to just ignore any keys that are not parameter names? Preferable a method that allows defaults to be specified.

很公平。但是,无论如何,在它的定义f或调用中,是否告诉 Python 忽略任何不是参数名称的键?最好是允许指定默认值的方法。

采纳答案by Abhijit

As an extension to the answer posted by @Bas, I would suggest to add the kwargs arguments (variable length keyword arguments) as the second parameter to the function

作为@Bas 发布的答案的扩展,我建议添加 kwargs 参数(可变长度关键字参数)作为函数的第二个参数

>>> def f (a=None, **kwargs):
    print a


>>> dct2 = {"a":"Foo", "b":"Bar"}
>>> f(**dct2)
Foo

This would necessarily suffice the case of

这必然满足以下情况

  1. to just ignore any keys that are not parameter names
  2. However, it lacks the default values of parameters, which is a nice feature that it would be nice to keep
  1. 忽略任何不是参数名称的键
  2. 但是,它缺少参数的默认值,这是一个很好的功能,最好保留

回答by Bas Swinckels

This can be done by using **kwargs, which allows you to collect all undefined keyword arguments in a dict:

这可以通过 using 来完成**kwargs,它允许您在 dict 中收集所有未定义的关键字参数:

def f(**kwargs):
    print kwargs['a']

Quick test:

快速测试:

In [2]: f(a=13, b=55)
13

EDITIf you still want to use default arguments, you keep the original argument with default value, but you just add the **kwargsto absorb all other arguments:

编辑如果您仍然想使用默认参数,则将原始参数保留为默认值,但您只需添加**kwargs以吸收所有其他参数:

In [3]: def f(a='default_a', **kwargs):
   ...:     print a
   ...:     

In [4]: f(b=44, a=12)
12
In [5]: f(c=33)
default_a

回答by Aviendha

If you cannot change the function definition to take unspecified **kwargs, you can filter the dictionary you pass in by the keyword arguments using the argspec function in older versions of python or the signature inspection method in Python 3.6.

如果您无法更改函数定义以采用未指定的 **kwargs,则可以使用旧版本的 python 中的 argspec 函数或 Python 3.6 中的签名检查方法,通过关键字参数过滤您传入的字典。

import inspect
def filter_dict(dict_to_filter, thing_with_kwargs):
    sig = inspect.signature(thing_with_kwargs)
    filter_keys = [param.name for param in sig.parameters.values() if param.kind == param.POSITIONAL_OR_KEYWORD]
    filtered_dict = {filter_key:dict_to_filter[filter_key] for filter_key in filter_keys}
    return filtered_dict

def myfunc(x=0):
    print(x)
mydict = {'x':2, 'y':3}
filtered_dict = filter_dict(mydict, myfunc)
myfunc(**filtered_dict) # 2
myfunc(x=3) # 3