In this tutorial, I will be focusing on arguments (
*args) and keyword arguments (
*kwargs) in Python.
I will teach you what args and kwargs are and, most importantly, how to use them—that is how to take in an unlimited number of arguments and keyword arguments in functions.
What Are Args?
*args are used to pass non-keyword arguments. Examples of non-keyword arguments are
*args are usually used as a measure to prevent the program from crashing if we don’t know how many arguments will be passed to the function. This is used in C++ as well as other programming languages.
What Are Kwargs?
**kwargs is a dictionary of keyword arguments. The
** allows us to pass any number of keyword arguments. A keyword argument is basically a dictionary.
An example of a keyword argument is
**kwargs are just like
*args except you declare the variables and the amount within the function arguments.
Where to Use Args and Kwargs
Args and kwargs are useful when you want to:
- Reduce code rewriting.
- Make your code readable.
- Reuse your code
Using Args and Kwargs in Functions
Let’s look at how kwargs and args are used in functions.
The function below takes in three arguments. The three arguments have been explicitly defined, so any more or less will cause an error in the program.
Let’s run the function. The function will add the three numbers, giving the following output:
What if we were to pass four arguments in the function instead of the required three? We will receive an error as shown below.
Read full tutorial at code.tutsplus