使用变量作为关键字来分配关键字参数的最 Pythonic 方式?
解决以下问题的最 Pythonic 方法是什么?从交互式 shell:
>>> def f(a=False):
... if a:
... return 'a was True'
... return 'a was False'
...
>>> f(a=True)
'a was True'
>>> kw = 'a'
>>> val = True
>>> f(kw=val)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got an unexpected keyword argument 'kw'
目前我正在使用以下方法解决它:
>>> exec 'result = f(%s=val)' % kw
>>> result
'a was True'
但它看起来很笨拙......
(python 2.7+ 或 3.2+ 解决方案都可以)
What is the most pythonic way to get around the following problem? From the interactive shell:
>>> def f(a=False):
... if a:
... return 'a was True'
... return 'a was False'
...
>>> f(a=True)
'a was True'
>>> kw = 'a'
>>> val = True
>>> f(kw=val)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got an unexpected keyword argument 'kw'
For the moment I'm getting around it with the following:
>>> exec 'result = f(%s=val)' % kw
>>> result
'a was True'
but it seems quite clumsy...
(Either python 2.7+ or 3.2+ solutions are ok)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用关键字参数解包:
Use keyword argument unpacking:
在许多情况下,如果您在关键字参数之前指定了所有参数,则可以直接使用
关键字参数,而不必将其指定为关键字。
Python 3 有一个仅关键字参数的语法,但事实并非如此默认情况下。
或者,基于 @zeekay 的答案,
如果您不想将 kw 存储为字典,例如,如果您还在其他地方将其用作字典查找中的键。
In many circumstances you can just use
as keyword arguments don't have to be specified as keywords, if you specify all arguments before them.
Python 3 has a syntax for keyword only arguments, but that's not what they are by default.
Or, building on @zeekay's answer,
if you don't want to store kw as a dict, for example if you're also using it as a key in a dictionary lookup elsewhere.