I do not understand the following example, let’s say I have these functions:
# python likes
def save(filename, data, **kwargs):
fo = openX(filename, "w", **kwargs) # <- #1
fo.write(data)
fo.close()
# python doesnt like
def save2(filename, data, **kwargs):
fo = openX(filename, "w", kwargs) # <- #2
fo.write(data)
fo.close()
def openX(filename, mode, **kwargs):
#doing something fancy and returning a file object
Why is #1 the right solution and #2 the wrong one? **kwargs is basically a dict, so if I want to pass down the argument to openX I think the correct way would be without ** and just giving the dict. But Python obviously doesn’t like the second one and tells me I gave 3 instead of 2 arguments.
So what’s the reason behind this?
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
kwargsto 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.