9. Code Documentation

Good code documentation explains what a function does, what inputs it expects, and what it returns. In Python, the most common place to document that information is in a docstring: a string literal placed immediately below a module, class, or function definition.

9.1. Basic docstrings

A basic docstring should describe the purpose of the function in plain language.

1def greet(name):
2    """Return a friendly greeting for a person."""
3    return f'Hello, {name}!'
4
5
6print(greet('Jane'))

You can inspect a function’s docstring with help() or by reading its __doc__ attribute.

1def square(n):
2    """Return the square of a number."""
3    return n * n
4
5
6print(square.__doc__)
7help(square)

9.2. Documenting parameters and return values

As functions become more important, the docstring should explain the parameters and the return value clearly.

 1def calculate_total(price, quantity, tax_rate=0.0):
 2    """
 3    Calculate the final total for a purchase.
 4
 5    Parameters:
 6        price: The price of one item.
 7        quantity: The number of items purchased.
 8        tax_rate: The tax rate as a decimal value.
 9
10    Returns:
11        The final price after tax.
12    """
13    subtotal = price * quantity
14    return subtotal * (1 + tax_rate)
15
16
17print(calculate_total(10.0, 3, 0.07))

9.3. Sphinx style

One common documentation style is the Sphinx or reStructuredText style. It is especially useful when your project uses Sphinx to build documentation automatically.

 1def divide(a, b):
 2    """
 3    Divide one number by another.
 4
 5    :param a: The numerator.
 6    :type a: float
 7    :param b: The denominator.
 8    :type b: float
 9    :return: The quotient ``a / b``.
10    :rtype: float
11    :raises ZeroDivisionError: If ``b`` is zero.
12    """
13    return a / b
14
15
16print(divide(9.0, 3.0))

9.4. Google style

Another common style is the Google docstring style. It is easy to read in source files and is supported by many editors, linters, and documentation tools.

 1def normalize_name(first_name, last_name):
 2    """
 3    Build a normalized full name.
 4
 5    Args:
 6        first_name: The first name to normalize.
 7        last_name: The last name to normalize.
 8
 9    Returns:
10        The normalized full name in title case.
11    """
12    return f'{first_name.strip().title()} {last_name.strip().title()}'
13
14
15print(normalize_name('  jane', 'DOE  '))

9.5. Which style should you use?

The most important rule is consistency. Pick one style for a project and use it throughout the codebase. If your team already uses Sphinx-generated API docs, Sphinx-style docstrings may fit naturally. If your team prefers simpler source-level readability, Google-style docstrings are a common choice.

9.6. What to document

Not every tiny function needs a long docstring. Focus on documenting functions whose purpose, inputs, outputs, side effects, or error cases might not be obvious from the code alone. Good documentation should clarify the code, not repeat it word for word.

9.7. Exercise

Write a function named calculate_shipping that accepts a package weight and destination zone and returns a shipping price. Document it twice:

  • once with a Sphinx-style docstring

  • once with a Google-style docstring

Make sure both versions explain the parameters, return value, and what happens if the weight is negative.