We can use the special syntax  *args  and  **kwargs within a function definition in order to pass any number of arguments to a function. In this article, we guide you on how to efficiently use args and kwargs in Python.

 

Functions are reusable a block of codes performing a specific task, they make the program more effective and modular. While defining a function in Python, we also specify the parameters it can accept which we later pass as arguments in the function call. However, there might be situations when you are not aware of the total number of arguments required or you suspect that later on, the function may need additional arguments.

Using *args In Python

In Python,  *args is used to pass an arbitrary number of arguments to a function. It’s worth mentioning that the single asterisk( ) is the most important element, the word arg is just a naming convention we can name it anything it will work as long as we have a ( * ) before it. This could be better understood by the following example, Let’s create a function which can add numbers,

This simple function adds the two number which we pass in the function call. But what if we want to add three numbers? Unfortunately passing three arguments in a function call will lead to an error.

Output: TypeError: total_sum() takes 2 positional arguments but 3 were given.

The  *args parameter is helpful in tackling such programming issues. Using   *args parameter gives the function ability to accepts any number of positional arguments.

Output:

Now we can pass as many arguments as we wish and the function will work for all of them, this makes our code more modular and flexible. As stated above the asterisk(*) is the most important syntax we can replace args with literally anything yet it will work.

Output:

Using **kwargs In Python

Keyword arguments allow passing arguments as parameter names. In order to design a function which takes an arbitrary number of keywords arguments  **kwargs in used as a parameter. It’s worth noting that the double-asterisk (**) is the key element here kwargs is just a convention you can use any word.

Output: {'a': 1, 'b': 2, 'c': 'Some Text'}

We received all the keywords and their values in a dictionary(Key: value) form and we can perform every dictionary operation on it. Note that dictionaries are unordered (On Python 3.5 and lower ) so your result may vary for a large dictionary. Let’s extend the function to perform some basic dictionary operations.

Output:

 

Using args and kwargs on the same function

Keywords arguments are making our functions more flexible. We can use both args and kwargs on the same function in python as follows:

Output:
Using args and kwargs on the same function In Python

Leave a Comment