These two special identifiers (named *args and **kwargs) should be put as the last two parameters in a function definition. Their names could be changed because it is just a convention to name them 'args' and 'kwargs', but it’s more important to sustain the order of the parameters and leading asterisks.
Those two special parameters are responsible for handling any number of additional arguments (placed next after the expected arguments) passed to a called function:
*args
– refers to a tuple of all additional, not explicitly expected positional arguments, so arguments passed without keywords and passed next after the expected arguments. In other words, *args collects all unmatched positional arguments;**kwargs
(keyword arguments) – refers to a dictionary of all unexpected arguments that were passed in the form of keyword=value pairs. Likewise, **kwargs collects all unmatched keyword arguments.
In Python, asterisks are used to denote that args and kwargs parameters are not ordinary parameters and should be unpacked, as they carry multiple items.
If you’ve ever programmed in the C or C++ languages, then you should remember that the asterisk character has another meaning (it denotes a pointer) which could be misleading for you.
Let's run the Python code presented in the right pane and study the output:
10
20
(40, 60, 30)
{'argument1': 50, 'argument2': '66'}
As you can see, the function's definition is expecting two arguments, a and b, and the definition is prepared to handle any number of additional arguments. Moreover, all other positional arguments are available in a tuple (as you may remember, a tuple is a sequence type, because the order matters in this case). Similarly, all unexpected keyword parameters are available in a dictionary type parameter.
Now if you take a look at the built-in print()
function definition, it becomes clear how this function can accept any number of arguments, and why there is an asterisk before one of the parameters:
def print(self, *args, sep=' ', end='\n', file=None):