Sub topic 14
Documenting a Function with a Docstring
This chapter assumes you can define functions with def, use parameters and return, and read basic type hints. It covers what a docstring is, how Python stores it, how to structure one, and the mistakes that make docstrings misleading.
What a docstring is
A docstring is a string literal placed as the first statement in a function body. Python stores it on the function object as the __doc__ attribute. Tools such as help(), editors and documentation generators read it from there.
def average(values: list[float]) -> float:
"""Return the arithmetic mean of values.
Raises ValueError if values is empty.
"""
if not values:
raise ValueError("values must not be empty")
return sum(values) / len(values)
print(average([2.0, 4.0, 6.0])) # 4.0
print(average.__doc__)
help(average)A docstring differs from a comment in one way. A comment (# ...) is discarded when Python compiles the file. A docstring survives at runtime and can be inspected by the caller.
Three rules decide whether a string counts as a docstring:
- It must be the first statement in the body. A string after other code is an ordinary expression that does nothing.
- It is conventionally written with triple double quotes (
"""), even for one line. This follows PEP 257. - It is a plain string. An f-string is not stored as a docstring, so you cannot build one dynamically that way.
def late(x):
y = x + 1
"""This is not a docstring."""
return y
print(late.__doc__) # NoneOne-line and multi-line docstrings
Use a one-line docstring when the function is simple enough that its name, parameters and a short sentence say everything. Keep the closing quotes on the same line.
def square(n: int) -> int:
"""Return n multiplied by itself."""
return n * nUse a multi-line docstring when you need to explain arguments, return values, errors or behavior. The structure is:
- A summary line that fits on one line.
- A blank line.
- Further detail, in whatever structure your project uses.
The summary line matters most. Tools that list functions often show only that line, so it should stand alone.
Writing the summary line
- Use the imperative mood: "Return the mean", not "Returns the mean" or "This function returns the mean".
- Describe what the function does for the caller, not how it does it.
- End with a period.
- Do not repeat the function name or the signature.
"""average(values) -> float"""adds nothing thathelp()does not already show.
Documenting parameters, returns and errors
A docstring for a function with any real behavior should answer three questions for a caller: what do I pass in, what do I get back, and what can go wrong. Three styles are common. All of them carry the same information, so choose one and apply it consistently across a project.
| Style | Section markers | Typical users |
|---|---|---|
| `Args:`, `Returns:`, `Raises:` | Many application codebases | |
| NumPy | Underlined headings such as `Parameters` and `Returns` | Scientific libraries |
| reStructuredText | `:param x:`, `:returns:`, `:raises E:` | Sphinx-based projects |
Here is the same function in Google style.
def clamp(value, /, low=0, *, high=100):
"""Limit value to the range from low to high.
Args:
value: The number to limit. Positional-only.
low: The smallest allowed result.
high: The largest allowed result. Keyword-only.
Returns:
low if value is below low, high if value is above high,
otherwise value itself.
"""
return max(low, min(value, high))
print(clamp(150)) # 100
print(clamp(-5)) # 0
print(clamp(150, high=120)) # 120Here it is in NumPy style.
def clamp(value, /, low=0, *, high=100):
"""Limit value to the range from low to high.
Parameters
----------
value : float
The number to limit. Positional-only.
low : float, optional
The smallest allowed result. Default is 0.
high : float, optional
The largest allowed result. Keyword-only. Default is 100.
Returns
-------
float
low if value is below low, high if value is above high,
otherwise value itself.
"""
return max(low, min(value, high))Type hints and docstrings together
If a function has type hints, do not repeat the types in the docstring. Duplicated types drift apart when someone edits one and forgets the other. Let the annotation state the type, and let the docstring state the meaning, the units, the allowed range and the edge cases.
def convert(amount: float, rate: float) -> float:
"""Convert amount using an exchange rate.
Args:
amount: Money in the source currency.
rate: Units of target currency per one unit of source currency.
Returns:
The amount in the target currency.
Raises:
ValueError: If rate is not positive.
"""
if rate <= 0:
raise ValueError("rate must be positive")
return amount * rate
print(convert(10.0, 1.1)) # 11.0The docstring here explains what rate means, which the type float cannot. That is the information a reader needs.
Documenting side effects and None
Chapter content on side effects applies here. If a function changes its arguments, writes output, or touches files, say so. A reader cannot see this from the signature.
def add_item(item, items=None):
"""Append item to items and return the list.
Args:
item: The value to add.
items: A list to modify in place. If None, a new list is created.
Returns:
The same list object that was passed in, or a new list if
items was None.
"""
if items is None:
items = []
items.append(item)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [2]The statement "modify in place" tells callers that their list changes. Without it, a caller could reasonably assume a copy is returned. Likewise, if a function returns None on purpose, state that its work is the side effect, for example "Print message to standard output."
Reading a docstring at runtime
Because the docstring is data, you can use it in code.
import inspect
def greet(name):
"""Return a greeting for name."""
return f"Hello, {name}!"
print(greet.__doc__) # Return a greeting for name.
print(inspect.getdoc(greet)) # Return a greeting for name.
print(inspect.signature(greet)) # (name)Prefer inspect.getdoc() over reading __doc__ directly. It removes the common leading indentation from multi-line docstrings, so the output looks the way you wrote it rather than carrying the extra spaces from the source file.
def demo():
"""First line.
Second paragraph, indented in the source.
"""
print(repr(demo.__doc__))
print(repr(__import__("inspect").getdoc(demo)))The first output contains the indentation spaces. The second does not.
Running Python with -OO strips docstrings, so __doc__ becomes None. Do not write code that depends on a docstring being present, such as using it as a user-facing help message.
Docstrings that run as tests
A docstring can include examples written as an interactive session. The doctest module finds lines starting with >>> and checks that the output matches.
def power(base, exponent=2):
"""Return base raised to exponent.
>>> power(5)
25
>>> power(2, 10)
1024
>>> power(exponent=3, base=2)
8
"""
return base ** exponent
if __name__ == "__main__":
import doctest
doctest.testmod()If the output stops matching, doctest.testmod() reports a failure. This keeps examples honest. Doctests suit small, deterministic functions. They are a poor fit for output that includes memory addresses, timestamps, or unordered sets, because the exact text changes between runs.
Common mistakes
- Stale docstrings. A function gains a parameter but the docstring does not. A wrong docstring is worse than none, because readers trust it. Update both in the same change.
- Restating the code.
"""Add one to x."""abovereturn x + 1tells the reader nothing new. Document intent, constraints and surprises. - Omitting
Raises. If a caller is expected to handle an exception, list it.averageraisesValueErrorfor an empty list, and a caller needs to know that. - Mixing styles. Using Google sections in one function and reStructuredText in another confuses both readers and documentation tools.
- Putting the string in the wrong place. A string after the first statement is silently ignored, as the
lateexample showed. - Documenting private details. Describe the contract the caller relies on, not internal variable names that may change.
Checklist for a good function docstring
- The first statement in the body is a triple-quoted string.
- The summary is one imperative sentence that fits on a line.
- Each parameter's meaning, units and limits are described, without repeating the type hint.
- The return value is described, including the
Nonecase if it matters. - Exceptions the caller should handle are listed.
- Side effects and in-place changes are stated.
- The text matches what the code does today.
Exercise
The function below has a docstring, but help(scale) shows no documentation. What is wrong, and how do you fix it? Also name one thing the docstring should say about the argument items.
def scale(items, factor):
result = []
"""Return a new list with each item multiplied by factor."""
for item in items:
result.append(item * factor)
return result
Show answer
The string is not the first statement in the body, because result = [] comes before it, so Python treats it as an ordinary expression and scale.__doc__ is None. Move the string to the first line inside the function. The docstring should also say that items is not modified, since a new list is returned, and could state that items must hold numbers or other values that support multiplication by factor.
Exercise
Write a Google-style docstring for def divide(a: float, b: float) -> float: that returns a / b and raises ZeroDivisionError when b is zero. Should the docstring repeat that a and b are floats?
Show answer
Example:
"""Divide a by b.
Args:
a: The dividend.
b: The divisor. Must not be zero.
Returns:
The quotient of a and b.
Raises:
ZeroDivisionError: If b is zero.
"""
The docstring should not repeat the float types, because the annotations already state them and a copy can drift out of date. It should describe meaning and constraints, such as that b must not be zero.