Aveek Das
Using the iterable unpacking operator in python - arguments in python

Understanding *args and *kwargs arguments in Python

April 2, 2021 by

In this article, I am going to talk in detail about the functions and arguments in Python. Python is one of the most popular and in-demand programming languages. Recently, a lot of programmers are gaining interest to work with python and as such, there is a huge community around it that is constantly evolving. Python is also considered to be one of the most flexible languages as it can be used to develop web-based applications, REST APIs as well as can also be used significantly in the scientific computation world to deal with data analysis and machine learning.

Python supports both object-oriented programming and procedural as well. It often depends on what type of application you are working with to choose which paradigm to follow. Personally, while performing data analysis or implementing any machine learning algorithm, I often end up writing code in small blocks and procedurally execute them However, if you are building complex web-based applications or REST API services, then choosing the object-oriented programming style can be much more useful. Let us understand in detail what *args and **kwargs are and how to use these as arguments in python.

Understanding Basic Functions in Python

In order to understand the use of arguments in python, we must know how to write functions first. Let me give a brief explanation of the writing function in Python. Functions are considered as the building blocks of any programming language. This is a foundational step that can be implemented in any programming language. Functions help us write modular code in smaller chunks as such it becomes much easier for us to isolate individual working parts and debug the code if there are any errors in it.

Writing a basic function in Python - arguments in Python

Figure 1 – Writing a basic function in Python (SourceCode)

This simple function will print Hello user to the screen when executed. Notice how the greet() function is triggered from the main() function upon execution of the python file. These are very simple functions and there are no arguments passed to these functions yet.

Now, let us enhance the above greet() function, to accept the name of the user as a parameter and print it to the screen.

Passing the username as argument in the function - arguments in Python

Figure 2 – Passing the username as an argument in the function (SourceCode)

When you execute the above code, the following output is received.

Output from the above code

Figure 3 – Output from the above code

Positional and Keyword Arguments in Python

So far, we have understood how to define simple functions and pass arguments to the functions and print them during the execution. Now, let’s take a step further and understand the two important types of arguments in python – the positional and the keyword arguments. The positional arguments are defined by the single asterisk before the parameter name, e.g. “*args”. The keyword arguments are defined by placing a double asterisk in front of the parameter name, e.g. “**kwargs”. An important point worth mentioning here is that the names args and kwargs are just placeholders and can be replaced with any other meaningful names. However, as a best practice, it is left as the same so that it’s easier for others to understand that the function accepts a positional or a keyword argument.

Positional Arguments in Python

These are the simplest type of arguments to pass in a function in python. You can define as many parameters in a function and then provide the arguments in the same order as defined in the function. The python program will read the arguments accordingly and perform the necessary actions. You can consider the following snippet to understand what a positional argument is used in a function.

Positional Argument example in python

Figure 4 – Positional Argument example in python (SourceCode)

The output from the above code block is as follows.

Output from the above code block

Figure 5 – Output from the above code block

As you can see in the output above, the arguments are printed in the order they are passed into the function. If you alter the position of the arguments while calling the function, then the output will change.

Also, in this case, you need to provide all three arguments while calling the function. In case, one or more arguments are missing, the function will throw an error during execution as there are no optional parameters defined. Let us now try to make the function a bit more flexible by making all three parameters optional. This can be done by assigning default values to the function as follows.

Specifying default values for the function parameters

Figure 6 – Specifying default values for the function parameters

Output from the above code block

Figure 7 – Output from the above code block

As you can see in the above figure, we have specified the argument for the parameters a and c but not for b. Notice how we have explicitly mentioned the parameter name c while assigning the argument. This is done because, by default, the positional argument will be assigned to the parameter b instead of c.

We can extend this functionality of providing positional arguments by declaring a single asterisk * operator, also known as the iterable unpacking operator.

Using the iterable unpacking operator in python - arguments in python

Figure 8 – Using the iterable unpacking operator in python (SourceCode)

When you run the above code, all the three users passed as arguments in the main function are iterated and the message is displayed for each of the users separately.

Output from the above code block

Figure 9 – Output from the above code block

Although we have defined only one parameter in the greet() function, the * operator takes the input as a positional argument and is then iterated using the for a loop. This is dynamic in nature as it can automatically handle multiple argument values and the programmer doesn’t need to define the parameter separately.

Keyword Arguments in Python

Now that we know what the positional arguments are and how to use those, using the keyword arguments will be quite easy. This is also something similar to the positional arguments, however, it is denoted by a **, a double asterisk in front of the parameter name also known as the dictionary unpacking operator.

Using the dictionary unpacking operator in pyton

Figure 10 – Using the dictionary unpacking operator in python (SourceCode)

The output from the above code block is as follows:

Output from the above code block

Figure 11 – Output from the above code block

As you can see in the figure above, the dictionary unpacking operator, or in simple words, we have used the **kwargs as an argument to the function and printed out the values on the console. It is evident from the above example that you can pass as many items as the arguments and all those will be unpacked and used by the function. This method is in many complex applications wherein the function is already developed by providing default values. However, if the user wants to override the default value, then it can be passed as an argument. This makes the parameter an optional one and also simplifies the life of the user as they need not worry about providing arguments to each of the parameters in the function.

Conclusion

In this article, we have seen how to define functions and use arguments in Python. In any programming language, we must define our functions correctly so that messages or data can be passed on from one function to another very easily. We have also seen what are *args and **kwargs in python and how to implement these while programming. As a best practice, you should always define as few parameters as required by your function. This helps to keep the function simpler and easy to implement. *args take in positional arguments in a function, whereas the **kwargs takes in keyword arguments.

Table of contents

Setting up Visual Studio Code for Python Development
How to debug Python scripts in Visual Studio Code
Deploy Python apps to Azure Functions using Visual Studio Code
Getting started with Amazon S3 and Python
Getting started with Pandas in Python
Working with Pandas Dataframes in Python
Exploring databases in Python using Pandas
Best practices to follow while programming in Python
Exporting data with Pandas in Python
Create REST APIs in Python using Flask
Working with JSON data in Python
Understanding *args and *kwargs arguments in Python
Aveek Das
Python

About Aveek Das

Aveek is an experienced Data and Analytics Engineer, currently working in Dublin, Ireland. His main areas of technical interest include SQL Server, SSIS/ETL, SSAS, Python, Big Data tools like Apache Spark, Kafka, and cloud technologies such as AWS/Amazon and Azure. He is a prolific author, with over 100 articles published on various technical blogs, including his own blog, and a frequent contributor to different technical forums. In his leisure time, he enjoys amateur photography mostly street imagery and still life. Some glimpses of his work can be found on Instagram. You can also find him on LinkedIn View all posts by Aveek Das

168 Views