Functions provide an effective way to package and reuse program code, as already
explained in Section 2.3. For example, suppose we find that we often want to read text
from an HTML file. This involves several steps: opening the file, reading it in, normal
izing whitespace, and stripping HTML markup. We can collect these steps into a func
tion, and give it a name such as get_text(), as shown in Example 4-1.
Example 4-1. Read text from a file.
import re
def get_text(file):
“””Read text from a file, normalizing whitespace and stripping HTML markup.”””
text = open(file).read()
text = re.sub(‘\s+’, ‘ ‘, text)
text = re.sub(r'<.*?>’, ‘ ‘, text)
return text
Now, any time we want to get cleaned-up text from an HTML file, we can just call
get_text() with the name of the file as its only argument. It will return a string, and we
can assign this to a variable, e.g., contents = get_text(“test.html”). Each time we
want to use this series of steps, we only have to call the function.
Using functions has the benefit of saving space in our program. More importantly, our
choice of name for the function helps make the program readable. In the case of the
preceding example, whenever our program needs to read cleaned-up text from a file
we don’t have to clutter the program with four lines of code; we simply need to call
get_text(). This naming helps to provide some “semantic interpretation”—it helps a
reader of our program to see what the program “means.” Notice that this example function definition contains a string. The first string inside a
function definition is called a docstring. Not only does it document the purpose of the
function to someone reading the code, it is accessible to a programmer who has loaded
the code from a file:
help(get_text)
Help on function get_text:
get_text(file)
Read text from a file, normalizing whitespace
and stripping HTML markup.
We have seen that functions help to make our work reusable and readable. They also
help make it reliable. When we reuse code that has already been developed and tested,
we can be more confident that it handles a variety of cases correctly. We also remove
the risk of forgetting some important step or introducing a bug. The program that calls
our function also has increased reliability. The author of that program is dealing with
a shorter program, and its components behave transparently.
To summarize, as its name suggests, a function captures functionality. It is a segment
of code that can be given a meaningful name and which performs a well-defined task.
Functions allow us to abstract away from the details, to see a bigger picture, and to
program more effectively.
The rest of this section takes a closer look at functions, exploring the mechanics and
discussing ways to make your programs easier to read.
