Passing a list of kwargs?
Solution 1
Yes. You do it like this:
def method(**kwargs):
print kwargs
keywords = {'keyword1': 'foo', 'keyword2': 'bar'}
method(keyword1='foo', keyword2='bar')
method(**keywords)
Running this in Python confirms these produce identical results:
{'keyword2': 'bar', 'keyword1': 'foo'}
{'keyword2': 'bar', 'keyword1': 'foo'}
Solution 2
As others have pointed out, you can do what you want by passing a dict. There are various ways to construct a dict. One that preserves the keyword=value
style you attempted is to use the dict built-in:
keywords = dict(keyword1 = 'foo', keyword2 = 'bar')
Note the versatility of dict
; all of these produce the same result:
>>> kw1 = dict(keyword1 = 'foo', keyword2 = 'bar')
>>> kw2 = dict({'keyword1':'foo', 'keyword2':'bar'})
>>> kw3 = dict([['keyword1', 'foo'], ['keyword2', 'bar']])
>>> kw4 = dict(zip(('keyword1', 'keyword2'), ('foo', 'bar')))
>>> assert kw1 == kw2 == kw3 == kw4
>>>
Solution 3
Do you mean a dict? Sure you can:
def method(**kwargs):
#do something
keywords = {keyword1: 'foo', keyword2: 'bar'}
method(**keywords)
Solution 4
So when I've come here I was looking for a way to pass several **kwargs in one function - for later use in further functions. Because this, not that surprisingly, doesn't work:
def func1(**f2_x, **f3_x):
...
With some own 'experimental' coding I came to the obviously way how to do it:
def func3(f3_a, f3_b):
print "--func3--"
print f3_a
print f3_b
def func2(f2_a, f2_b):
print "--func2--"
print f2_a
print f2_b
def func1(f1_a, f1_b, f2_x={},f3_x={}):
print "--func1--"
print f1_a
print f1_b
func2(**f2_x)
func3(**f3_x)
func1('aaaa', 'bbbb', {'f2_a':1, 'f2_b':2}, {'f3_a':37, 'f3_b':69})
This prints as expected:
--func1--
aaaa
bbbb
--func2--
1
2
--func3--
37
69
Related videos on Youtube
jwanga
Updated on July 08, 2022Comments
-
jwanga almost 2 years
Can I pass a list of kwargs to a method for brevity? This is what i'm attempting to do:
def method(**kwargs): #do something keywords = (keyword1 = 'foo', keyword2 = 'bar') method(keywords)
-
Benj about 5 yearsI was trying to pass kwargs from one function to another function's kwargs. Great question!
-
-
Ned Deily over 14 yearsOr: keywords = dict(keyword1 = 'foo', keyword2 = 'bar')
-
David Z over 14 yearsah, I wasn't paying attention. Should be better now.
-
magu_ over 7 yearsAs of
python 3.5
theFoo(**arg1, **arg2)
is possible -
Benj about 5 yearsThe
**
unpacking operator can be used to pass kwargs from one function to another function's kwargs. Consider this code: (newlines don't seem to be allowed in comments)def a(**kw): print(kw)
, anddef b(**kw): a(kw)
. This code will generate an error because kwargs is actually a dictionary, and will be interpreted as a regular argument of thedict
type. Which is why changingdef b(**kw): a(kw)
todef b(**kw): a(**kw)
will unpackkw
and resolve the errors.