Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

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

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use keyword argument unpacking:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...