最简洁的Python方法:用变量作为关键字赋值参数?
什么是最符合Python风格的方法来解决下面这个问题?在交互式命令行中:
>>> 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+ 的解决方案都可以)