Python 在函数调用期间将参数添加到 kwargs 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27892356/
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
Add a parameter into kwargs during function call?
提问by Markus Meskanen
Is there a way to add key-value-pair into kwargs during the function call?
有没有办法在函数调用期间将键值对添加到 kwargs 中?
def f(**kwargs):
print(kwargs)
# ...
pre_defined_kwargs = {'a': 1, 'b': 2}
f(**pre_defined_kwargs, c=3)
Or even change the existing arguments?
或者甚至改变现有的论点?
f(**pre_defined_kwargs, b=3) # replaces the earlier b=2
These two examples don't work, as they raise error
这两个示例不起作用,因为它们会引发错误
>>> f(**pre_defined_kwargs, c=3)
SyntaxError: invalid syntax
Pointing at the comma in between the arguments
指向参数之间的逗号
采纳答案by Martijn Pieters
For Python versions < 3.5, you need to place the **kwargs
variable keyword argument last:
对于 Python 版本 < 3.5,您需要将**kwargs
变量关键字参数放在最后:
f(c=3, **pre_defined_kwargs)
See the Callsexpression syntax; in all forms of the grammar the "**" expression
rule is placed last. In other words, using anything after the **expression
syntax is a syntax error.
请参阅调用表达式语法;在所有形式的语法中,"**" expression
规则都放在最后。换句话说,在**expression
语法之后使用任何东西都是语法错误。
If you want to update the dictionary with new values, you can use the dict()
callable; it can create a copy of your existing dictionary andupdate keys in that, provided the keys are also valid Python identifiers (start with a letter or underscore, and only contain letters, digits and underscores):
如果你想用新值更新字典,你可以使用dict()
callable; 它可以创建现有字典的副本并在其中更新键,前提是键也是有效的 Python 标识符(以字母或下划线开头,并且只包含字母、数字和下划线):
f(c=3, **dict(pre_defined_kwargs, b=42))
Here b=42
sets a newvalue for the 'b'
key. This same syntax can be used to add keys too, of course.
这里为键b=42
设置一个新值'b'
。当然,同样的语法也可用于添加键。
You cannot use the same key both in the **expression
mapping and explicitly; that'll raise a TypeError
. Again, from the documentation already linked:
您不能在**expression
映射中和显式使用相同的键;这将提高一个TypeError
. 同样,从已经链接的文档中:
If the syntax
**expression
appears in the function call,expression
must evaluate to a mapping, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in bothexpression
and as an explicit keyword argument, aTypeError
exception is raised.
如果语法
**expression
出现在函数调用中,则expression
必须计算为映射,其内容被视为附加关键字参数。如果关键字同时出现在expression
和 作为显式关键字参数,TypeError
则会引发异常。
Demo:
演示:
>>> def f(**kwargs):
... print(kwargs)
...
>>> pre_defined_kwargs = {'a': 1, 'b': 2}
>>> f(c=3, **pre_defined_kwargs)
{'a': 1, 'c': 3, 'b': 2}
>>> dict(pre_defined_kwargs, b=42)
{'a': 1, 'b': 42}
>>> f(c=3, **dict(pre_defined_kwargs, b=42))
{'a': 1, 'c': 3, 'b': 42}
This restriction has been lifted as of Python 3.5 (thanks to PEP-448 -- Additional Unpacking Generalizations; you can now freely mix the order of argument types and use multiple **mapping
references in a call (using distinct mappings). Keywords still have to be unique across all arguments applied; you still can't 'override' arguments that appear more than once.
从 Python 3.5 开始,此限制已取消(感谢PEP-448 -- Additional Unpacking Generalizations;您现在可以自由混合参数类型的顺序并**mapping
在调用中使用多个引用(使用不同的映射)。关键字仍然必须是唯一的跨应用的所有参数;您仍然不能“覆盖”出现多次的参数。
回答by dm03514
>>> f(c=3, **pre_defined_kwargs)
{'c': 3, 'a': 1, 'b': 2}