How to use *args and **kwargs in Python

How to use *args and **kwargs in Python

How to use *args and **kwargs in Python

I have come to see that most new Python programmers have a hard time figuring out the *args and **kwargs magic variables. So what are they?
First of all, let me tell you that it is not necessary to write *args or **kwargs specifically. Only the * (asterisk) is necessary. You could also write *var and **vars writing *args and **kwargs is just a convention.

So now, let’s take a look at *args first.

Usage of *args

*args and **kwargs are mostly used in function definitions. They allow you to pass an unspecified number of arguments to a function, so when writing the function definition, you do not need to know how many arguments will be passed.

  • *args is used to send a non-keyworded, variable-length argument list to the function.
  • **kwargs is used to send a keyworded, variable-length argument list to the function.

Example:

def test_var_args(f_arg, *argv):
    print('first normal arg:', f_arg)
    for arg in argv:
        print('another arg through *argv:', arg)

test_var_args('Hello', 'Coders', 'Learn', 'Python')

# Output
# first normal arg: Hello
# another arg through *argv: Coders
# another arg through *argv: Learn
# another arg through *argv: Python

Usage of **kwargs

**kwargs allows you to pass keyworded, variable-length arguments to a function. You should use **kwargs if you want to handle named arguments in a function.

def greet_me(**kwargs):
    for key, value in kwargs.items():
        print("{0} = {1}".format(key, value))

greet_me(name="Karan")

# Output
name = Karan
def greet_me(**kwargs):
    for key, value in kwargs.items():
        print("{0} = {1}".format(key, value))

greet_me(name="John", age=30, city="New York", profession="Engineer")

# Output
name = John
age = 30
city = New York
profession = Engineer

So you can see how we handled a keyworded argument list in our function. This is just the basics of **kwargs and you can see how useful it is. Now let’s talk about how you can use *args and **kwargs to call a function with a list or dictionary of arguments.

Using *args and **kwargs to call a function

We can also use *args and **kwargs to call a function by unpacking a list or dictionary of arguments.

def test_args_kwargs(arg1, arg2, arg3):
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("arg3:", arg3)

Now you can use *args or **kwargs to pass arguments to this little function. Here’s how to do it:

# first with *args
args = ("two", 3, 5)
test_args_kwargs(*args)

# Output
arg1: two
arg2: 3
arg3: 5

# now with **kwargs:
kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
test_args_kwargs(**kwargs)

# Output
arg1: 5
arg2: two
arg3: 3

Order of using *args **kwargs and formal args

so if want to use all three of these in function then the order is

some_func(fargs, *args, **kwargs)

When to use them?

It really depends on what your requirements are. The most common use case is when making function decorators (discussed in another chapter). Moreover it can be used in monkey patching as well. Monkey patching means modifying some code at runtime. Consider that you have a class with a function called get_info which calls an API and returns the response data. If we want to test it we can replace the API call with some test data. For instance:

import someclass
def get_info(self, *args):
    return "Test data"

someclass.get_info = get_info

I am sure that you can think of some other use cases as well.

Conclusion

In conclusion, *args and **kwargs are indispensable tools for enhancing the flexibility and adaptability of Python functions. Understanding when and how to use them opens up a myriad of possibilities, from creating elegant decorators to performing dynamic runtime code modifications. Use these versatile features to write more robust and adaptable Python code.

Author

  • Naveen Pandey Data Scientist Machine Learning Engineer

    Naveen Pandey has more than 2 years of experience in data science and machine learning. He is an experienced Machine Learning Engineer with a strong background in data analysis, natural language processing, and machine learning. Holding a Bachelor of Science in Information Technology from Sikkim Manipal University, he excels in leveraging cutting-edge technologies such as Large Language Models (LLMs), TensorFlow, PyTorch, and Hugging Face to develop innovative solutions.

    View all posts
Spread the knowledge
 
  

Join the Discussion

Your email will remain private. Fields with * are required.