Functions are a handy tool in programming. They reduce the amount of code we as a programmer have to write. With functions, we can make a piece of code reusable. To get different results from a function, we need to give it various inputs. Here is where arguments are coming in.
In the code below, I have a simple example of a greeting function. It takes the surname as an argument and returns a hello message for that person.
But what happens if we add more arguments than asked?
In that case, we will get a syntax error. To solve this problem, python gives us two unique arguments: *args and **kwargs.
For what stands *args and **kwargs?
*args stands for non-keyword arguments and **kwargs for keyword arguments. In your code, you don’t have to use the same names (args and kwargs). Importantly are the asterisks in front of the argument name.
So when do we use them?
We use them when we are unsure about the number of arguments in our function.
Let’s get back to our example. What happens if we write *surnames as an argument inside the greeting function?
In this case, we can add as many non-keyword arguments as we want into our greeting function. All these input values get passed over as a tuple.
But what if we want to pass over keyword arguments? For that, we use **kwargs. Let’s have a look at another example.
In this code snippet, we use named arguments like surname, name, age, and email address to pass over the information of a person to our biography function. The data that gets handed over is a dictionary.
Things to remember!
- args and **kwargs are helpful when we don’t know how many arguments we want to use in a function
- args are used for non-keyword arguments. The data passed over with *args is a tuple.
- kwargs are used for keyword arguments. The data passed over with **kwargs is a dictionary.
- You can use both simultaneously, but you have to write *args before **kwargs. Otherwise, you’ll get a syntax error. E.g. function(*args, **kwargs)
I hope you enjoyed this little introduction to *args and **kwargs in python.