How to use *args And **kwargs In Python¶
usage of * args and **kwargs in functions¶
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.
Example of python *args and **kwargs¶
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
In above code case1¶
- default values for *args are empty tuple and for **kwargs are empty dictionary.
- *args and **kwargs are not mandatory
- we can use tuple functionalities on "args" and dict functinalities on "kwargs".
In above code case2¶
- All extra arguments are stored in "args" in a tuple format.
- All key, value arguments are stored in "kwargs" in a dict format.
In above code case3¶
- when we use *args, **kwargs in function "f1(*args, **kwargs)" arguments are unpacked from the tuple and dictionary f1(*args, **kwargs) = "f1(1,3,4, d=100)"
When to use python *args and **kwargs ?
It is useful when number of parameters in a function are unknown
Example usage of python *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
*args
and **kwargs
in python classes as well just like above. Note: Data type of *args is tuple and Data type of **kwargs in dictionary.
References: 1. https://docs.python.org/2/faq/programming.html#id15