How to pass **kwargs inside a Python function

In one of the previous tutorials about the Python computer programming language, we learned how to make use of the *args syntax to pass arguments inside a function. Through this article, you are going to learn how to make use of the **kwargs Python syntax to automatically pass keyword based arguments inside a function.

Before going any further with this article, make sure to launch a new Python interactive shell in your own operating system so you can practice the theory being shared in here by yourself.

Once you have managed to launch a new Python interactive shell in your own operating system, declare a function by following the syntax being shared below.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

def display_data(name='oltjano', age=25, profession='blogger'):
    print(name, age, profession)

The function which is declared above, takes three keyword based arguments. Based on my personal experience with the Python computer programming language, the coder can easily make use of the following syntax to unpack a dictionary and pass it to a function like the one we have already created.

def display_data(**kwargs)

Now declare the following dictionary object in your Python computer programming language.

student = {'name':'john', 'age':42, 'profession':'coder'}

Once you have managed to define the dictionary being shown above in your own Python interactive console, make use of the following syntax to pass the keyword based arguments to the function.

display_data(**student)

Once the above piece of the Python code gets executed on my Python computer programming language’s interactive shell, the following output is being displayed on my console.

('john', 42, 'coder')

Final thoughts

Through this tutorial the reader learned how he or she can make use of the **kwargs syntax to automatically pass keyword based arguments to a function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Leave a Reply

Your email address will not be published. Required fields are marked *