使用变量作为关键字分配关键字参数的最有效方法?

使用变量作为关键字分配关键字参数的最有效方法?

问题描述:

解决以下问题的最pythonic方式是什么?在交互式外壳程序中:

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...

(python 2.7+或3.2+解决方案都可以)

(Either python 2.7+ or 3.2+ solutions are ok)

使用关键字参数解压:

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

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