Python language basics 32: positional and keyword arguments in a function
July 25, 2015 Leave a comment
Introduction
In the previous post we discussed how to provide optional arguments to a function. We saw how easy it was to assign a default value to a function argument using the assignment operator ‘=’. The caller could optionally ignore those arguments so that the default ones would be used within the function body. Alternatively the caller could override the defaults and provide its own argument values.
In this post we’ll look at another feature related to function arguments: positional and keyword arguments.
Positional function arguments
Consider the following function with 3 parameters:
def show_greeting(name, age, location): print("Welcome " + name + "! You are " + str(age) + " years old and live in " + location)
Here’s an example of calling the function:
show_greeting("Andras", 36, "Stockholm")
This is nothing special, we’ve seen functions and function calls before. This way of passing the arguments is called positional. Each argument in the function call, i.e. “Andras”, 36 and “Stockholm”, is paired up with the respective argument in the function signature: name, age, location. If we mix up the order of the arguments then we can get a funny result:
show_greeting("Stockholm", 36, "Andras")
…which prints…
Welcome Stockholm! You are 36 years old and live in Andras
Keyword arguments
You can specifically state in the function call which value belongs to which argument. In this case you can even mix up the order in which the arguments are passed:
show_greeting(location="Stockholm", age=36, name="Andras")
…which prints…
Welcome Andras! You are 36 years old and live in Stockholm
One advantage of keyword arguments is better documentation of your code. It will be easier for another programmer reviewing the code to understand which argument does what. Otherwise they may have to view the actual function code to see what the arguments mean.
If you want to mix the two strategies then the positional arguments must come first:
show_greeting("Andras", 36, location="Stockholm")
Read all Python-related posts on this blog here.