将 kwargs 显式传递给函数参数
Python 中有没有一种方法可以将字典显式传递给函数的 **kwargs 参数?我正在使用的签名是:
def f(*, a=1, **kwargs): pass # same question with def f(a=1, **kwargs)
我尝试通过以下方式调用它:
my_dict=dict(b=2)
f(kwargs=my_dict) # wrong, kwargs receives {'kwargs': {'b': 2}} instead of {'b': 2}
f(**kwargs=my_dict) # SyntaxError: invalid syntax
f(kwargs=**my_dict) # SyntaxError: invalid syntax
我想这样做的原因是我传入的字典可能包含键a
,而我不希望它污染 f
的参数 a
:
overlap_dict=dict(a=3,b=4)
f(**overlap_dict) # wrong, 'a' is 3, and 'kwargs' only contains 'b' key
f(a=2, **overlap_dict) # TypeError: f() got multiple values for keyword argument 'a'
用 f
中的字典替换 **kwargs
签名对我来说不是一个选择。
Is there a way in Python to pass explicitly a dictionary to the **kwargs
argument of a function? The signature that I'm using is:
def f(*, a=1, **kwargs): pass # same question with def f(a=1, **kwargs)
I tried to call it the following ways:
my_dict=dict(b=2)
f(kwargs=my_dict) # wrong, kwargs receives {'kwargs': {'b': 2}} instead of {'b': 2}
f(**kwargs=my_dict) # SyntaxError: invalid syntax
f(kwargs=**my_dict) # SyntaxError: invalid syntax
The reason I want to do this is that the dictionary I pass in may contain the key a
, and I don't want it to pollute the f
's argument a
:
overlap_dict=dict(a=3,b=4)
f(**overlap_dict) # wrong, 'a' is 3, and 'kwargs' only contains 'b' key
f(a=2, **overlap_dict) # TypeError: f() got multiple values for keyword argument 'a'
Replacing **kwargs
with a dictionary in f
's signature is not an option for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不想更改
f
来接受更多参数,您可以简单地使a
获取一个列表,并且第一个条目用于f
,第二个条目用于kwargs
,例如:您也可以使用字典执行类似的操作:
或者,这确实会更改
f
的参数输入,但我认为有点清楚了。我能想到的有2种情况。首先,如果您知道a
将始终在kwargs
中设置:另一种情况是,如果您希望
a
是否传递给它是可选的kwargs:If you don't want to change
f
to accept more parameters, you could simply makea
take a list and the first entry is forf
, and the second entry is forkwargs
, for instance:You can also do something similar with a dictionary:
Alternatively, this does change
f
's parameter inputs, but I think it's a bit clearer. There are 2 cases I can think of. First, if you know thata
will always be set inkwargs
:The other case is if you want it to be optional whether
a
passes tokwargs
:用
a
更新kwargs
并传递它。例如,假设您有一个值a=1
,那么就这样做。Update the
kwargs
witha
and then pass it. Example, say you have a valuea=1
, then do like this.您可以临时(或永久,如果您愿意,只需删除最后一行)修改
f
以将kwargs
作为关键字参数。请注意,这是一个有点邪恶的黑客行为,所以我建议您首先尝试其他解决方法。这打印:
You can temporarily (or permanently, if you want – just remove the last line) modify
f
to takekwargs
as a keyword argument. Note that this is a somewhat evil hack, so I would urge you to try other workarounds first.This prints: