I am trying to understand the difference between *args and **args in function definition in python. In the below example, *args works to pack into a tuple and calculate the sum.
>>> def add(*l):
... sum = 0
... for i in l:
... sum+=i
... return sum ...
>>> add(1,2,3)
6
>>> l = [1,2,3]
>>>add(*l)
6
for ** args,
>>> def f(**args):
... print(args)
...
>>> f()
{}
>>> f(de="Germnan",en="English",fr="French")
{'fr': 'French', 'de': 'Germnan', 'en': 'English'}
>>>
I see that it takes parameters and turns into a dictionary. But I do not understand the utility or other things that could be helpful when using ** args. In fact, I dont know what *args and **args are called(vararg and ?)
Thanks
When you use two asterisks you usually call them **kwargs
for keyword arguments. They are extremely helpful for passing parameters from function to function in a large program.
A nice thing about keyword arguments is that it is really easy to modify your code. Let's say that in the below example you also decided that parameter cube
is also relevant. The only thing you would need to do is add one if statement
in my_func_2
, and you would not need to add a parameter to every function that is calling my_func_2
, (as long as that functions has **kwargs
).
Here is a simple rather silly example, but I hope it helps:
def my_func_1(x, **kwargs):
if kwargs.get('plus_3'):
return my_func_2(x, **kwargs) + 3
return my_func_2(x, **kwargs)
def my_func_2(x, **kwargs):
#Imagine that the function did more work
if kwargs.get('square'):
return x ** 2
# If you decided to add cube as a parameter
# you only need to change the code here:
if kwargs.get('cube'):
return x ** 3
return x
Demo:
>>> my_func_1(5)
5
>>> my_func_1(5, square=True)
25
>>> my_func_1(5, plus_3=True, square=True)
28
>>> my_func_1(5, cube=True)
125
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With