Here’s another article in the Functions in Python series. Today we’ll be talking about keyword arguments.
If you haven’t read the previous parts yet, feel free to do so. Here they are:
6) Mutable Optional Parameters
All the parameters that we’ve been using so far, both mandatory and optional, are the so-called positional parameters. This is because when we call a function, the arguments must be passed to it in the same order (at the same positions) as in the parameter list. But there is a way around it. We can use arguments in any order, provided we pass them along with the parameter names. These are the so-called keyword arguments.
Positional Parameters Only
Here’s an example with just positional parameters:
def calculate_area(kitchen, bathroom, hall = 0, room1 = 0, room2 = 0, room3 = 0, show_unit = True):
area = str(kitchen + bathroom + hall + room1 + room2 + room3)
if show_unit:
area += " m2"
print(area)
calculate_area(20, 8)
calculate_area(20, 8, 9, 18, 21, 16)
calculate_area(20, 8, 0, 0, 0, 0, False)
The parameters kitchen and bathroom are mandatory. If we use just the two, all the default values will be used for the other parameters.
All the other parameters are optional. But they are all positional. This means that if we want to set a different value to any of them, we must also use all the parameters that precede it. That’s the case in the last call. Although we only want to set the value of show_unit to False, we have to explicitly pass all the parameters before, with the same values as the defaults. This is necessary in order to maintain the positions of the parameters.
Here is the output:
28 m2
92 m2
28
Keyword Arguments Only
Now, let’s call the same function with keyword arguments. Now the order is not important and we can skip any optional parameters we want. We only have to use the mandatory parameters somewhere. Here are some examples:
calculate_area(hall = 5, bathroom = 8, show_unit = False, kitchen = 20)
calculate_area(room1 = 20, room2 = 25, kitchen = 20, bathroom = 8)
And here’s the output:
33
73 m2
Positional and Keyword Arguments Side by Side
We can also use both positional and keyword arguments at the same time. The important thing to remember is to place the positional ones first, at their positions, and then we can put the others in any order or skip any of the optional ones if we want:
calculate_area(20, 8, room1 = 30, show_unit = False)
And here’s the output:
58