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

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

Add a parameter into kwargs during function call?

pythonpython-3.xkwargskeyword-argument

提问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 **kwargsvariable keyword argument last:

对于 Python 版本 < 3.5,您需要将**kwargs变量关键字参数放在最后

f(c=3, **pre_defined_kwargs)

See the Callsexpression syntax; in all forms of the grammar the "**" expressionrule is placed last. In other words, using anything after the **expressionsyntax 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=42sets 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 **expressionmapping and explicitly; that'll raise a TypeError. Again, from the documentation already linked:

您不能在**expression映射中和显式使用相同的键;这将提高一个TypeError. 同样,从已经链接的文档中:

If the syntax **expressionappears in the function call, expressionmust evaluate to a mapping, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in both expressionand as an explicit keyword argument, a TypeErrorexception 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 **mappingreferences 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}