Python *args and **kwargs With Example

Python *args and **kwargs

Python Function Arguments

Python allows us to define three types of arguments for a function:

  1. Formal Arguments, for example def add(a, b)
  2. Variable number of non-keyworded arguments using *args, for example def add(*args)
  3. Variable number of keyworded arguments or named arguments using **kwargs, for example def add(**kwargs).

Some important points about function arguments.

  • When we define a function arguments, the order should be formal arguments followed by *args and **kwargs.
  • It’s not mandatory to use the names args and kwargs, we can use other names too. However, it’s the convention to use them. It will make your code easy to read and understand.
  • The args variable is of type tuple. We can pass a tuple as a function argument to map with args.
  • The kwargs variable is of type dict. So we can pass a dictionary as an argument to map with kwargs.

Why do we need *args and **kwargs?

Let’s say we have a function to add two numbers:

Now we want to extend this to add three numbers. We can’t just change this function because it might be getting used at some other places and it will be a breaking change. So, we introduce another function to add three numbers.

You see where I am going with this, right? Since we have the option to specify a variable number of arguments for a function, we can define a generic function to add numbers.

Python *args example

Let’s define a generic function to add numbers using *args variables.

What is the type of *args and **kwargs?

Output:

Python **kwargs example

Let’s define a function to show the usage of **kwargs variables.

Output:

Passing Tuple and Dictionary for *args and **kwargs mapping

Let’s see how to pass tuple values to map with args and dictionary elements to the kwargs variable.

Output:

Notice the use of * while using a tuple to map its values to args. Similarly, ** is used to map dict elements to the kwargs variable.

When to use *args and **kwargs

You can use them in any function where you are expecting a variable number of arguments. However, they are very useful in two specific cases – Simulating a function response, and writing a generic decorator function.

Simulating a function response with *args and **kwargs

Let’s say we have an API class defined like this:

We can create a test simulator function and map it to the API function to generate a test response.

Let’s see what happens when we use our API functions now.

Output:

Decorator function for *args and **kwargs

Let’s see how we can define a decorator function to log function variables.

Now, we can use this decorator function with any other function to log their arguments to console.

Output:

You can checkout complete python script and more Python examples from our GitHub Repository.

By admin

Leave a Reply