We can retrieve positional and named arguments in any number of *args
.
Getting named arguments as dictionaries
Only named arguments can be obtained as a dictionary, which allows you to store the names in keys:
def g(**kwargs):
return kwargs
g(x=1, y=2, z=None)
# {'x': 1, 'y': 2, 'z': None}
We can refer to an argument that receives this dictionary as kwargs
(keyword arguments).
We write the keyword arguments after all the usual positional ones:
*args
before the first argument with the default value**kwargs
after the last argument with the default value
Let us define a function that takes all kinds of arguments:
def f(x, y, *args, kx=None, ky=42, **kwargs):
return (x, y, args, kx, ky, kwargs)
f(1, 2, 3, 4, kx='a', ky='b', kz='c')
# (1, 2, (3, 4), 'a', 'b', {'kz': 'c'})
Do not worry. It is rare for a function to use all of these features in real-life code. Nevertheless, it is essential to understand how each type of argument declaration works and how to combine them.