Kwargs vs args in Python
This article introduces the differences between arguments passed to a function in Python with args and kwargs.
The problem
In Python, we can pass arguments to a function with “args” and “kwargs”.
Imagine you want to create a function that computes the product of all its arguments. The naive approach is the following:
def product(a=1, b=1, c=1, d=1, e=1, f=1):
return a * b * c * d * e * f
If we want to pass exactly 6 arguments, this function will work properly. However, we can doubt that this will be possible if we want to pass a greater number of arguments.
A solution would be to pass the arguments in a tuple, a list, or any other data structure. We will see that this is possible natively with args and kwargs.
Args
Let’s see how we can transform our product function into a function with args.
def product(*args):
res = 1
for arg in args:
res *= arg
return res
product(1, 2, 3, 4, 5, 6)
Args being a tuple, we can now add as many arguments as we want to the function, the result will be the product of all these arguments.
args (and Kwargs) is only a variable name, it is possible to write the function
def product(*dict)
if you prefer. The important thing is the asterisk.
Kwargs
There is no big difference between kwargs and args. Kwargs means Keyword Arguments.
def product(**kwargs):
res = 1
for key, value in kwargs.items(): # kwargs is a dictionary
res *= value
return res
product(a=1, b=2, c=3, d=4, e=5, f=6)
Kwargs is a dictionary. We can now add as many key/value pairs as we want to the function, the result will be the product of all these values.
For this purpose, args is of course a better choice than kwargs.
Kwargs and Args in the same function.
Remark
In python, “optional arguments” (with default values) are placed at the end.
def product(a, b, c=1, d=1, e=1, f=1):
return a * b * c * d * e * f
product(1, 2)
Il n’est pas possible de passer c=1
avant b
. Cela retounerait une erreur.
Both kwargs and args
As seen, there is an order in the arguments of a function. The order is the following:
- Standard arguments
- Optional arguments
- *args
- **kwargs
Thus, for the following function :
def showNumbers(a, b, *c, **d):
print(a)
print(b)
print(c)
print(d)
showNumbers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, postFinalNumber = 19, finalNumber = 20)
Results in:
1
2
(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
{'postFinalNumber': 19, 'finalNumber': 20}