The trick is that though the symbol (**
) is the same, the operator is different:
def print_kwargs(**all_args):
# Here ** marks all_args as the name to assign any remaining keyword args to
print all_args
an_argument = {"test": 1}
# Here ** tells Python to unpack the dictionary
print_kwargs(**an_argument)
If we don't explicitly unpack our arguments in the call to print_kwargs
then Python will throw a TypeError
, because we have provided a positional argument that print_kwargs
doesn't accept.
Why doesn't Python automatically unpack a dictionary into kwargs
? Mostly because "explicit is better than implicit" - while you could do automatic unpacking for a **kwarg
-only function, if the function had any explicit arguments (or keyword arguments) Python would not be able to automatically unpack a dictionary.