Search code examples
pythonkeyword-argumentargument-unpacking

Why does this print `3 {}` and not `2 {'a': 3}`?


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.


Solution

  • 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.