Most pythonic way of assigning keyword arguments u

2019-01-15 00:28发布

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)

2条回答
可以哭但决不认输i
2楼-- · 2019-01-15 01:07

Use keyword argument unpacking:

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

>>> f(**kw)
<<< 'a was True'
查看更多
Explosion°爆炸
3楼-- · 2019-01-15 01:17

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.

查看更多
登录 后发表回答