Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a list of kwargs?

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) 
like image 473
jwanga Avatar asked Sep 30 '09 06:09

jwanga


People also ask

How do you pass multiple Kwargs?

Python 3.5+ allows passing multiple sets of keyword arguments ("kwargs") to a function within a single call, using the `"**"` syntax.

What does * args and * Kwargs mean?

*args passes variable number of non-keyworded arguments and on which operation of the tuple can be performed. **kwargs passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed.

What is the correct way to use the Kwargs statement?

The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks ( ** ) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.


1 Answers

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'} 
like image 71
Peter Avatar answered Sep 19 '22 10:09

Peter