Python *args and **kwargs
Python has a special syntax, * (single asterisk) and ** (double asterisks), that lets you pass a variable number of arguments to a function. By convention, these are written as *args and **kwargs, but only the asterisks are important; you could equally write *vars and **vars to achieve the same result.
*args is used to pass a non-keyworded variable-length argument list to your function. **kwargs lets you pass a keyworded variable-length of arguments to your function.
In a traditional Python function, you must explicitly define the number of arguments and parameters.
But what if the number of parameters does not match the number of arguments? For example, if we define one parameter but pass in none:
And if we pass in two arguments but only define one parameter:
In Python a function only works if the number of arguments matches the number of parameters.
By using *args we can attach a variable-length number of arguments into our function.
This is useful when we don’t know how many arguments we need to pass in.
If we want to pass a keyworded variable length of arguments to a function, we use **kwargs. It lets us handle named arguments in our function.
As an example:
If we wanted to return just the key/value we can use the items() method.
*args and **kwargs together
Often *args and **kwargs are used together in a function where we have at least one required argument. In these instances, order matters. Positional-only parameters must come first, so *args and **kwargs are placed after any required arguments.
All three of the following will work with this function:
*args and **kwargs are powerful Python features that can make writing functions a much more enjoyable task. They are also common when extending an existing method in a subclass.
Just remember, normal, positional-only parameters come first. A simple way to remember this is always add *args and **kwargs at the end of your required arguments.
So if we have one required argument, write:
If there are two required arguments:
And so on!
Want to learn how to build web applications and RESTful APIs in Python? Check out my books Django for Beginners and REST APIs with Django.