def f(a=2, **b):
print(a,b)
f(**{'a':3})
Why does this print 3 {}
and not 2 {'a': 3}
?
I can understand why it printed 3 {}
if it was f(a=3)
but I don't understand the output in this case.
def f(a=2, **b):
print(a,b)
f(**{'a':3})
Why does this print 3 {}
and not 2 {'a': 3}
?
I can understand why it printed 3 {}
if it was f(a=3)
but I don't understand the output in this case.
The unpacking operator, when used on a dict, passes the dict's contents as keyword arguments.
In other words, the following two lines are functionally identical:
f(a=3)
f(**{'a':3})
Since a
is getting passed explicitly as a keyword argument, the default value of 2
is overwritten. And since no other arguments are passed, the **b
argument is left empty.
The call f(**{'a':3})
is same as f(a=3)
, so the value of a
is 3 and not the default 2. For b
, using the unpacking operator **
, it means to save all the other mapping variable into it, as there is no one, it values an empty dict
a
is 3b
is empty dict, {}
So it prints 3 {}
To use b
you need to pass argument named differently as a
# both print: 3 {'foo': 'bar', 'number': 100}
f(**{'a':3, 'foo':'bar', 'number':100})
f(a=3, foo='bar', number=100)