The world’s leading publication for data science, AI, and ML professionals.

Args and Kwargs in Python – Function Calling Made Easy

Understand how functions can return multiple values in full.

Photo by MORAN on Unsplash
Photo by MORAN on Unsplash

It was during my first read of the fastai book that I came across the keywords *args and **kwargs in function calls. Naturally, I was ever so curious as to learn another aspect of the Programming language I love so much so I began to reasearch. It turns out, these two combined really make some complex functioning calling in Python 3 seem like a child’s play!

Ever since my research about these two operators (yes, they are called unpacking operators in the technical language we speak), I have been using them in my day to day experiments with projects and I find they’re pretty cool. So now, I’m writing this article for you to learn about these cool concepts in case you’re missing out!

Let’s go!

What are unpacking operators?

The single and double asterisk unpacking operators were introduced sometime in Python 2. But after the Python 3.6 release, they have become even more powerful in use.

In short, the unpacking operators are operators that unpack the values from iterable objects in Python. The single asterisk operator * can be used on any kind of iterable in the language, while the double asterisk operator ** can only be used on various operations on dictionaries.

Let’s go ahead and see an example. We’ll define some helper variables that we’ll be using throughout this Tutorial to explore the functionalities of the two operators.

nums = [1, 2, 3]
alphs = ['a', 'b', 'c']
nums_d = {1: 'one', 2: 'two', 3: 'three'}
alphs_d = {'a': 'First', 'b': 'Second', 'c' : 'Third'}

Now let’s go ahead and learn more about them by seeing them in actions!

How do we use the unpacking operators?

First, let’s experiment on our list nums.

Here is the unpacked version of the list:

print(*nums)

OUTPUT:
1 2 3

Let’s do another one! We’ll unpack the next list of character/strings we have alphs.

print(*alphs)
OUTPUT:
a b c

Notice the similarities? You must be getting some idea of what this operator is doing to these lists now, right? It’s turning iterable lists into individual elements that can be processed individually by some function we can pass these values to!

Let’s go ahead and see that usecase now. It should become clear by the time we see the examples about using functions to manipulate these values unpacked by the operator.

Using the unpacking operators with Python functions

We can unpack a string by using this simple call:

ex = 'Args and Kwargs'
print(*ex)
OUTPUT:
A r g s   a n d   K w a r g s
# each individual character can be processed separately

We can also do it with lists of elements. Let’s define a simple function that adds three numbers.

def sum_of_nums(n1, n2, n3):
    print(n1 + n2 + n3)

Now let’s go ahead and pass our list of numbers nums to this function BUT with the unpacking operator attached.

sum_of_nums(*nums)

OUTPUT:
6

See the magic?! This is so very cool. We can also do the same thing with the dictionary we defined earlier.

Let us first define a function to make a string concatenation and print the results to the user. *args stands for arguments.

def concat_str(*args):
    res = ''
    for s in args:
        res += s
    print(res)

Now, let’s go ahead and call it with our unpacking operator attached to the dictionary alphs.

concat_str(*alphs)
OUTPUT:
abc

This looks very similar to the above output.

What is the conclusion? Unpacking operators allow us to use and manipulate as we need the individual element in any iterable. This way, we can pass a complex list of lists or dictionaries and the operator can let us use the elements of the lists and key/values of the dictionaries in our custom function.

Here, see what the operator does to a list of string.

ex = 'Args and Kwargs'
print([*ex])

OUTPUT:
['A', 'r', 'g', 's', ' ', 'a', 'n', 'd', ' ', 'K', 'w', 'a', 'r', 'g', 's']

It returns an iterable(a new list) with the element of the individual string unpacked!

Going one step forward with **kwargs

**kwargs stands for keyword arguments.

Kwargs is an unpacking operator that we use with dictionaries. Let’s define a new function that concatenates two or more dictionaries together.

def concat_str_2(**kwargs):
    result = ''
    for arg in kwargs:
        result += arg
    return result

Now, we can call this function with any number of dictionaries.

print(concat_str_2(**alphs_d))

OUTPUT:
abc

Oops! The keys from our dictionary gets concatenated here. But we may want to concatenate the values for our keys, right?

We can do that by iterating over the values just like we do with any normal dictionary.

# concatenating the values of the kwargs dictionary
def concat_str_3(**kwargs):
    result = ''
    for arg in kwargs.values():
        result += arg
    return result

print(concat_str_3(**alphs_d))

Can you guess what the output will be?

OUTPUT:
FirstSecondThird

Remember our two dictionaries from before? We can easily combine them by using the ** operator.

alphanum = {**nums_d, **alphs_d}
print(alphanum)
OUTPUT:
{1: 'one', 2: 'two', 3: 'three', 'a': 'First', 'b': 'Second', 'c': 'Third'}

Lastly, we can also concat dictionaries together directly.

concat_str_3(a = 'Merge', b = ' this ', c = "dictionary's values")

Here, we pass key – value pairs to our function. Try to think what our output will be before you look below.

OUTPUT:
"Merge this dictionary's values"

That is it! You now know everything these two awesome operators from Python!

One last thing

The order in which we define function arguments in its definition is important to remember. We can’t mess up the order or our Python interpreter will throw an error!

This is the correct order of arranging the arguments in a function defintion:

# correct order of arguments in function
def my_cool_function(a, b, *args, **kwargs):
    '''my cool function body'''

The order is like this: Standard variable arguments, *args arguments and then the **kwargs arguments.


The complete jupyter notebook associated with this tutorial can be found in this repo! https://github.com/yashprakash13/Python-Cool-Concepts

yashprakash13/Python-Cool-Concepts

If you want to learn more about the series of articles I’m doing on fastai, in which I’m documenting my journey with this library, visit this article. 🙂


Do you want to learn to make a deep learning model in less than 20 lines of code and quickly deploy it as a REST API? Get my FREE guide here!

Connect with me on Twitter and LinkedIn.


Related Articles