使用变量作为关键字分配关键字参数的最有效方法? [英] Most pythonic way of assigning keyword arguments using a variable as keyword?

查看:87
本文介绍了使用变量作为关键字分配关键字参数的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决以下问题的最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'

这篇关于使用变量作为关键字分配关键字参数的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆