Friday, February 4, 2022

*args and **kwargs

*args is used when you don’t have any idea about how many arguments you will use. If you don’t know how many parameter you require, then * args is the way to go. Suppose you have decided to go shopping, but you don’t know how many items you are going to buy or how much you are going to spend. So, the expenditure is undecided. You have no idea about how many products you will buy so a function cannot be created with defined number of elements. When using *args, you are using a tuple with a potential of additional arguments. This tuple is initially empty, and no error is generated if no argument is provided.

def sum_func(a, *args):

s = a + sum(args)

print(s)

sum_func(10)

sum_func(10,20)

sum_func(10,20,30)

sum_func(10, 20, 30, 40)

Output:

10

30

60

100

>>>

**kwargs stands for keyworded arguments(of variable length), and is used when you don’t have any idea about how many keyword arguments you would be using. **kwargs builds a dictionary of key value pairs. These types of arguments are often used when working with different external modules and libraries. The double star ‘**’ in **kwargs allows any number of keyworded arguments to pass through. As the name suggests, in keyword argument a name is provided to the variable while passing it to the function similar to dictionary where keywords are associated with values.

def shopping(**kwargs):

print(kwargs)

if kwargs:

print('you bought', kwargs['dress'])

print('you bought', kwargs['food'])

print('you bought', kwargs['Shampoo'])

shopping(dress = 'Frock',Shampoo ='Dove',food = 'Pedigree Puppy')

Output:

{'dress': 'Frock', 'Shampoo': 'Dove', 'food': 'Pedigree Puppy'}

you bought Frock

you bought Pedigree Puppy

you bought Dove

It is important to note that since **kwargs is similar to dictionary, if you try to iterate over it then it may or may not print in the same order. As far as the name is concerned, you can use any name instead of args or kwargs. These names are recommended, but are not mandatory. However, it is important to use * for positional arguments and ** for keyword arguments. This is necessary.

Share:

0 comments:

Post a Comment