Kwargs allow you to pass keyword arguments to a function. They are used when you are not sure of the number of keyword arguments that will be passed in the function. Kwargs can be used for unpacking dictionary key, value pairs. This is done using the double asterisk notation ( ** ).
Python 3.5+ allows passing multiple sets of keyword arguments ("kwargs") to a function within a single call, using the `"**"` syntax.
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.
kwargs is variable name used for keyword arguments, another variable name can be used. The important part is that it's a dictionary and it's unpacked with the double asterisk operator ** .
In the second example you provide 3 arguments: filename, mode and a dictionary (kwargs
). But Python expects: 2 formal arguments plus keyword arguments.
By prefixing the dictionary by '**' you unpack the dictionary kwargs
to keywords arguments.
A dictionary (type dict
) is a single variable containing key-value pairs.
"Keyword arguments" are key-value method-parameters.
Any dictionary can by unpacked to keyword arguments by prefixing it with **
during function call.
Expanding on @gecco 's answer, the following is an example that'll show you the difference:
def foo(**kwargs):
for entry in kwargs.items():
print("Key: {}, value: {}".format(entry[0], entry[1]))
# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})
# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")
Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails
The **
syntax tells Python to collect keyword arguments into a dictionary. The save2
is passing it down as a non-keyword argument (a dictionary object). The openX
is not seeing any keyword arguments so the **args
doesn't get used. It's instead getting a third non-keyword argument (the dictionary). To fix that change the definition of the openX
function.
def openX(filename, mode, kwargs):
pass
For #2 args will be only a formal parameter with dict value, but not a keyword type parameter.
If you want to pass a keyword type parameter into a keyword argument You need to specific ** before your dictionary, which means **args
check this out for more detail on using **kw
http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
Because a dictionary is a single value. You need to use keyword expansion if you want to pass it as a group of keyword arguments.
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