Python *args and **kwargs

 

*args and **kwargs are two python magic variables which are commonly used to pass arguments into the functions. The magic doesn’t lives in the name(args and kwargs) but in the *(asterisk). These variables are used when you are not sure of the number of arguments to be passed to the function.

*args – Used to pass multiple non-key-worded arguments

**kwargs – Used to pass multiple key-worded arguments

What key-worded means will be clarified in the below examples.

*args Usage

Example: abc.py

>>def abc(*args):
>>    for ar in args:
>>        print(ar)
>>
>>abc(5,6,7,"asd","ewr",5.7)

Output:
5
6
7
asd
ewr
5.7

**kwargs Usage

Example: abc.py

>>def abc(**kwargs):
>>    for key,value in kwargs.items():
>>        print("Key = {} , Value = {}".format(key,value))
>>        
>>abc(int1=5,int2=6,int3=7,str1 = "asd",str2= "ewr",doub1 = 5.7)


Output:
Key = int3 , Value = 7
Key = str2 , Value = ewr
Key = str1 , Value = asd
Key = int1 , Value = 5
Key = doub1 , Value = 5.7
Key = int2 , Value = 6

The values passed in second example have names assigned to each value i.e. its a key value pair, these arguments are called key-worded arguments.

Leave a Reply

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