如何忽略传递给函数的意外关键字参数? [英] How does one ignore unexpected keyword arguments passed to a function?
问题描述
假设我有一些功能,f
:
def f (a=None):
print a
现在,如果我有像dct = {"a":"Foo"}
这样的字典,我可以调用f(**dct)
并得到打印结果Foo
.
Now, if I have a dictionary such as dct = {"a":"Foo"}
, I may call f(**dct)
and get the result Foo
printed.
但是,假设我有一本字典dct2 = {"a":"Foo", "b":"Bar"}
.如果我拨打f(**dct2)
我会得到
However, suppose I have a dictionary dct2 = {"a":"Foo", "b":"Bar"}
. If I call f(**dct2)
I get a
TypeError: f() got an unexpected keyword argument 'b'
足够公平.但是,无论如何,在f
的定义中或在调用它时,是否要告诉Python仅忽略不是参数名称的任何键?最好是一种可以指定默认值的方法.
Fair enough. However, is there anyway to, in the definition of f
or 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.
推荐答案
作为@Bas发布答案的扩展,我建议将kwargs参数(可变长度关键字参数)添加为函数的第二个参数
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
>>> def f (a=None, **kwargs):
print a
>>> dct2 = {"a":"Foo", "b":"Bar"}
>>> f(**dct2)
Foo
这足以满足
- 只忽略不是参数名称的任何键
- 但是,它缺少参数的默认值,这是一个很好的功能,可以很好地保留
这篇关于如何忽略传递给函数的意外关键字参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!