Skip to main content

*args and **kwargs in Python

 So here I'm gonna explain what are the *args and **kwargs, and what is their use of it. let's Begin

You can *args and **kwargs are the magic variables. so first of all it is not necessary to write *args and **kwargs, and only an asterisk (*) is needed also you can write *something and **somethings. it is just for understanding we take *args and **kwargs

*args:

Assume we have a function name sum which takes two parameters X and Y and this function return sum of those two values. function code is below:

def sum(x,y):
return x+y
print(sum(10,3)) # 13

now we need function which can give us sum of three values so what if we pass three arguments in this function?

TypeError: sum() takes exactly 2 arguments (3 given)

So we need to change our function definition but how many times have you will change it?

so for this type of situation, there is a magic variable called *args

function definition using *args is below:

def sum(x,y,*args):
result = x + y
for i in args:
result += i
return result
print(sum(10,3,14,23,25)) # 75

so this was basic knowledge about *args, I hope you understand the use of *args, Now let's move on to **kwargs

**kwargs:

You should use **kwargs if you want to handle named arguments in a function, let me explain with example.

def details(**kwargs):
for key, value in kwargs.items():
print(f"{key} = {value}")

details(name="apnacodingadda",subject="Programming",topic="*args and **kwargs")

#output:
# name = apnacodingadda
# subject = Programming
# topic = *args and **kwargs

So as you can see we handle a bunch of arguments with help of **kwargs so this was basically about **kwargs.

Remember When we are using *args then Extra parameters (which *args handling those parameter) are stored in tuple and **kwargs stored those arguments in dictionary (as there are key,value pair)

If you want to use them both and want some other must-pass parameter in function then the order would like this --   def func(other,*args,**kwargs) 

When to use them?

There are lot of use of *args and **kwargs . the most common use is in making function decorators.

and also these are use in Monkey Patching (modifying code at run time) 

So that was all basics about *args and **kwargs 


Thank You 😊😊




Comments

Popular posts from this blog

Products Which I like

headphone Buy now Camera Buy now

Makefile

 You may have seen file named Makefile or you may have type command like make, make install. so what is this file Makefile and what are this command. let's discuss about it.

What is Docker?

 Hello Everyone , Today we'll talk about what is docker ?, how to use it ? and why you should use it ?, then let's begin...