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

anon picture anon · Aug 8, 2011 · Viewed 10.6k times · Source

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)

Answer

zeekay picture zeekay · Aug 8, 2011

Use keyword argument unpacking:

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

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