Keyword arguments

Published

2023-07-31

Keyword arguments

Some of what we’ll do with files involves using keyword arguments.

Thus far, when we’ve called or defined functions, we’ve only seen positional arguments. For example, math.sqrt(x) and list.append(x) each take one positional argument. Some functions take two or more positional arguments. For example, math.pow(x, y), takes two positional arguments. The first is the base, the second is the power. So this function returns x raised to the y power (x^y). Notice that what’s significant here is not the names of the formal parameters but their order. It matters how we supply arguments when calling this function. Clearly, 2^3 (8) is not the same as 3^2 (9). How does the function know which argument should be used as the base and which argument should be used as the exponent? It’s all based on their position. The base is the first argument. The exponent is the second argument.

Some functions allow for keyword arguments. Keyword arguments follow positional arguments, and are given a name when calling the function. For example, print() allows you to provide a keyword argument end which can be used to override the default behavior of print() which is to append a newline character, \n, with every call. Example:

print("Cheese")
print("Shop")

prints “Cheese” and “Shop” on two different lines, because the default is to append that newline character. However

print("Cheese", end=" ")
print("Shop")

prints “Cheese Shop” on a single line (followed by a newline), because in the first call to print() the end keyword argument is supplied with one blank space, " ", and thus, no newline is appended. This is an example of a keyword argument.

In the context of file input and output, we’ll use a similar keyword argument when working with CSV files (comma separated values).

open('my_data.csv', newline='')

This allows us to avoid an annoying behavior in Python’s CSV module in some contexts. We’ll get into more detail on this soon, but for now, just be aware that we can, in certain cases, use keyword arguments where permitted, and that the syntax is as shown: positional arguments come first, followed by optional keyword arguments, with keyword arguments supplied in the form keyword=value. See: The newline='' keyword argument, below.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).