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)
Python 3.5+ allows passing multiple sets of keyword arguments ("kwargs") to a function within a single call, using the `"**"` syntax.
*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.
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.
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With