Understanding Args and Kwargs in Python

, , Comments Off on Understanding Args and Kwargs in Python

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.

*args are used to pass non-keyword arguments. Examples of non-keyword arguments are fun(3,4), fun("foo","bar").

*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.

**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 fun(foo=2,bar=7).

**kwargs are just like *args except you declare the variables and the amount within the function arguments.

Args and kwargs are useful when you want to:

  • Reduce code rewriting.
  • Make your code readable.
  • Reuse your code

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