Most pythonic way of assigning keyword arguments using a variable as keyword?

余生长醉 提交于 2019-11-26 14:32:32

问题


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)


回答1:


Use keyword argument unpacking:

>>> kw = {'a': True}

>>> f(**kw)
<<< 'a was True'



回答2:


In many circumstances you can just use

f(kw)

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,

kw = 'a'
f(**{kw: True})

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.



来源:https://stackoverflow.com/questions/6976658/most-pythonic-way-of-assigning-keyword-arguments-using-a-variable-as-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!