how to use *args and **kwargs in python

how to use *args and **kwargs in python

Python programming language is a simple and powerful language. It provides simple syntax with powerfull features. In this article we will discuss how to use *args and **kwargs in python.

*args and **kwargs are magic powers of python. we use *args for unpacking of arguments  and **kwargs for unpacking of keyword arguments.

Note: We can use *arguments instead *args and **keywordargs instead **kwargs, we can use any name in place of "args", "kwargs". Most developers use it as *args and **kwargs.

using *args and **kwargs in functions

def print_recieved_data(num1, num2, *args, **kwargs):
print("num1 = ", num1)
print("num2 = ", num2)
print("*args = ", args)
print("**kwargs = ", kwargs)

# case 1
print_recieved_data(10, 20)
# Output:
num1 = 10
num2 = 20
*args = ()
**kwargs = {}

# case 2
print_recieved_data(10, 20, 30, 40, name="Anji", age=23)
# Output:
num1 = 10
num2 = 20
*args = (30, 40)
**kwargs = {"name": "Anji", "age": 23}

def f1(a, b, c, d):
return a+b+c+d
def f2(*args, **kwargs):
return f1(*args, **kwargs)

# case3
sum = f2(1,3,4, d=100)
print sum
# Output: 108

From the above code we can observe the follwing.

From case1

  1. default values for *args are empty tuple and for **kwargs are empty dictionary. 
  2. *args and **kwargs are not mandatory
  3. we can use tuple functionalities on "args" and dict functinalities on "kwargs".

From case2

  1. All extra arguments are stored in "args" in a tuple format.
  2. All key, value arguments are stored in "kwargs" in a dict format.

From case3

  1. when we use *args, **kwargs in function "f1(*args, **kwargs)" arguments are unpacked from the tuple and dictionary
  2. f1(*args, **kwargs) = "f1(1,3,4, d=100)"

Use case:

  • used when number of parameters in a function are unknown

using *args and **kwargs in classes

class Parent(object):
    def __init__(self, a, b):
        # do something
        print(a, b)

class Child(Parent):
    def __init__(self, *args, **kwargs):
        # do something
        super(Parent, self).__init__(*args, **kwargs)
       # do something

When we are using inheritance the above case may encounters some times. Consider the above code for example.

Read Next: Basic understanding of class in python

Read Prev: iterators in python

Blog Archive