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