0%

More Expressive Functions

Documenting a Function

The previous lesson introduced the REPL as a place to explore Python one instruction at a time. We will keep using it here, this time to inspect information stored inside .

The functions in this chapter are becoming more flexible. They have defaults, named settings, and optional values. As that flexibility grows, someone using a function needs to know its rules without reading every line of its body.

For example, a percentage function needs a positive total. It returns a number, and it raises an error when that rule is broken. We can record those facts as the function’s promise:

  • what values it expects;

  • what it returns;

  • any important rules or errors.

The implementation shows how the function works. Python gives us a way to store a short explanation with the function itself. Before we use it, you need one new way to write a .

Triple quotes for strings

So far, you have written strings between one pair of quotes, such as "hello". A string can also begin and end with three double quotes:

Try it

The still has the type str. The triple quotes only change how you write it.

One useful difference is that a triple-quoted string can continue on a new line:

Try it

Python also accepts three single quotes. In this course, we will use three double quotes for function documentation because that is the usual Python style.

When the first string becomes documentation

A triple-quoted string is not automatically documentation. Its position inside the function gives it a special job.

When a string is the first statement in a function, Python keeps it as the function’s docstring. A docstring explains what other code can rely on when it uses the function.

You learned in Fundamentals I that raise stops a function and reports why it could not return a normal result. The docstring and validation can sit together:

def percentage(score, total):
    """Return score as a percentage of a positive total."""
    if total <= 0:
        raise ValueError("total must be positive")
    return score / total * 100

Here, the triple-quoted string is the first statement, so it becomes the docstring. It explains the result and the positive-total rule in one sentence.

Python’s help() function can display that documentation:

help(percentage)

Describe the promise, not every step

This docstring is weak:

"""Divide score by total, multiply by 100, and return it."""

It repeats the implementation. A stronger docstring names the promise and the important restriction:

"""Return score as a percentage of a positive total."""

What is the best purpose of a function docstring?

Explore docstrings in the REPL

The panel beside this lesson is a Python REPL. At its >>> prompt, try these commands one at a time:

help(len)
help(print)
help("python land".strip)

These functions already have docstrings. You do not need to understand every detail that help() shows. Look for the function’s name, the values it accepts, and the first sentence that describes its result.

The docstring itself is also available through a function’s __doc__ attribute. Compare these two REPL instructions:

len.__doc__
help(len)

len.__doc__ evaluates to the stored string, so the REPL displays that value. help(len) presents the same documentation in a fuller help view.

Now give your own function a docstring. Enter these lines in the REPL, then press Enter once more on the empty ... line to finish the function:

def double(number):
    """Return number multiplied by two."""
    return number * 2

Then inspect and use it:

double.__doc__
help(double)
double(6)

Try changing the docstring and defining the function again. The next call to help(double) will show your new description.