Python Docstrings, Annotations and Function Design
What you will learn
- How to write a docstring, and how to read one with
help() - Type annotations for parameters and results, and what they do (and do not do)
- Examples inside docstrings that Python can check (
doctest) - Principles of good function design
- Guard clauses, validation and
assert
1. Docstrings
A docstring is a string placed as the first statement of a function. It documents what the function does. Python stores it in the function's __doc__, and the help() function shows it:
def area(width, height):
"""Return the area of a rectangle."""
return width * height
print(area.__doc__)
help(area)
Return the area of a rectangle.
Help on function area in module __main__:
area(width, height)
Return the area of a rectangle.
Use triple double quotes, even for one line. Tools such as help, editors and documentation generators all read docstrings, so they are more useful than comments for explaining what a function is for. A function without one has __doc__ equal to None.
Quick check: where must a docstring be placed?
As the first statement in the function body, right after the def line.
What to write
The Python style guide for docstrings (PEP 257) suggests:
- One line for simple functions: an imperative sentence ending with a full stop, such as
"""Return the area of a rectangle.""". Say what it does, not "This function...". - For more detail, write a one-line summary, a blank line, then the details.
def clamp(value, low, high):
"""Limit value to the range low..high.
Args:
value: the number to limit.
low: the smallest allowed result.
high: the largest allowed result.
Returns:
low if value < low, high if value > high, otherwise value.
"""
return max(low, min(value, high))
print(clamp.__doc__.splitlines()[0])
Limit value to the range low..high.
The Args: and Returns: layout is one popular convention (there are others). Choose one style and use it everywhere. Describe what the parameters mean, what is returned, and anything surprising: errors raised, or whether the function changes its input.
Docstrings also work on modules, classes and methods (chapter 13).
2. Type annotations
You can annotate the parameters and the result with their expected types. Annotations are hints for readers and tools:
def add(a: int, b: int = 0) -> int:
return a + b
print(add.__annotations__)
print(add(1, 2))
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
3
a: intsays "ashould be an integer".= 0is the default, written after the annotation.-> intsays what the function returns.
The annotations are stored in __annotations__, but Python does not check them when the program runs:
print(add("a", "b"))
print(add(1.5, 2.5))
ab
4.0
Both calls worked, although the hints said int. The hints are used by editors (for autocompletion), and by checking tools such as mypy, which read the code without running it and warn about mismatches. Lesson 19.1 goes much deeper.
A fuller example:
from typing import Optional
def greet(name: str, times: int = 1, *, loud: bool = False) -> str:
out = ("Hello, " + name + "! ") * times
return out.upper() if loud else out
def find(items: list[str], target: str) -> Optional[int]:
return items.index(target) if target in items else None
print(find(["a", "b"], "b"), find(["a"], "z"))
1 None
Optional[int] means "an int or None". Annotations also show in help() and in inspect.signature:
import inspect
print(inspect.signature(add))
(a: int, b: int = 0) -> int
3. Examples that are tested: doctest
You can put examples in a docstring, written like an interactive session (>>> for the call, then the expected result). The doctest module runs them and checks the answers, so your documentation cannot go out of date without being noticed:
def clamp(value, low, high):
"""Limit value to the range low..high.
>>> clamp(15, 0, 10)
10
>>> clamp(-5, 0, 10)
0
>>> clamp(5, 0, 10)
5
"""
return max(low, min(value, high))
import doctest
print(doctest.testmod())
TestResults(failed=0, attempted=3)
attempted=3 means three examples ran, and failed=0 means all matched. If you changed the function to min(low, ...) by mistake, the failure message would show the example, what was expected and what came out. From the command line, python -m doctest -v myfile.py does the same for a whole file. Doctests suit small, clear examples; larger test suites are lesson 18.2.
4. Principles of good functions
A function is easy to use when it is small, clear and honest.
| Principle | What it means |
|---|---|
| One job | the function does one thing, and its name says which |
| A clear name | a verb for actions (send_email), is_ or has_ for yes/no (is_valid) |
| Few parameters | more than about three or four is a warning sign: group related values (a dictionary, a named tuple, a dataclass) |
| No hidden effects | it uses its arguments and returns a result, and does not change globals or its input unless that is its job |
| Predictable return | it always returns the same kind of thing (lesson 11.2) |
| Short | if you cannot see it on one screen, consider splitting it |
def bad(items, flag, mode, verbose, extra, more):
return None
A signature like bad is hard to call correctly: nobody remembers the order of six unlabelled values. Prefer keyword-only options (lesson 11.3), or bundle related ones together.
Pure functions
A pure function depends only on its arguments and has no side effects: the same inputs always give the same output, and nothing else changes. Pure functions are the easiest to test and reuse:
def pure(xs):
return sorted(xs)
def impure(xs):
xs.sort()
data = [3, 1, 2]
print(pure(data))
print(data)
impure(data)
print(data)
[1, 2, 3]
[3, 1, 2]
[1, 2, 3]
pure left data alone and returned a new list. impure changed data and returned None. Both can be right, but if a function changes its input, say so in its name or docstring (sort_in_place, or "Sort items in place.").
5. Guard clauses and early returns
Handle the odd cases first with an early return, so that the main logic is not buried in nested if blocks (lesson 11.1):
def process(order):
if not order:
return "empty"
if "paid" not in order:
return "unpaid"
return "shipped"
print(process({}), process({"x": 1}), process({"paid": True}))
empty unpaid shipped
Each early return is a guard clause: it deals with one special case and leaves. The normal case runs at the end, un-indented.
6. Checking arguments
If a function gets a bad value, it should fail clearly and early rather than give a wrong answer. Python's way is to raise an exception (chapter 14):
def total_price(prices, tax_rate=0.0):
"""Return the sum of prices with tax added."""
if tax_rate < 0:
raise ValueError("tax_rate must not be negative")
return sum(prices) * (1 + tax_rate)
print(total_price([10, 20]))
print(total_price([10, 20], 0.1))
total_price([1], -1)
30.0
33.0
ValueError: tax_rate must not be negative
The error message names the problem and the rule, which is what the caller needs. Use ValueError for a value that is the right type but unacceptable, and TypeError for the wrong type.
assert: checking your own assumptions
An assert statement checks that something you believe is true. If not, it raises AssertionError, with an optional message:
assert area(3, 4) == 12
assert area(2, 2) == 5, "area of 2x2 should be 4"
AssertionError: area of 2x2 should be 4
Use assert for checking your own code (tests, and things that "can never happen"). Python can run with assertions turned off (with the -O option), so never use assert to check user input or to enforce rules: raise an exception for that.
7. Comments or docstrings?
- A docstring says what the function is for and how to use it.
- A comment (starting with
#) says why a line does something surprising. - Do not write comments that only repeat the code, such as
x = x + 1 # add one to x. If a function needs many comments to be understood, it probably needs a better name, or to be split into smaller functions.
Worked example: a well-designed function
A function turns a list of marks into a short report. We give it a docstring with tested examples, annotations, validation and a clear return.
def summarise(marks: list[float], pass_mark: float = 50) -> dict:
"""Summarise a list of marks.
>>> summarise([40, 60, 80])
{'count': 3, 'average': 60.0, 'passed': 2}
>>> summarise([])
{'count': 0, 'average': 0.0, 'passed': 0}
"""
if pass_mark < 0:
raise ValueError("pass_mark must not be negative")
if not marks:
return {"count": 0, "average": 0.0, "passed": 0}
return {
"count": len(marks),
"average": sum(marks) / len(marks),
"passed": sum(1 for m in marks if m >= pass_mark),
}
import doctest
print(doctest.testmod())
print(summarise([45, 55, 65, 75], pass_mark=60))
TestResults(failed=0, attempted=2)
{'count': 4, 'average': 60.0, 'passed': 2}
| Feature | Why it helps |
|---|---|
| docstring with examples | shows how to call it, and doctest proves it still works |
| annotations | tell readers and tools what goes in and out |
if not marks: guard |
the empty list is handled first, so there is no division by zero |
the ValueError check |
a bad pass_mark fails loudly |
| always returns a dictionary | the caller never has to check for None |
| no changes outside | it only reads marks |
The marks and pass limits are made up.
Common mistakes
- No docstring, or one that only repeats the name.
- Believing annotations are checked by Python. They are not.
- Using
assertto check user input. - Functions that do several jobs, or have many unlabelled parameters.
- Hidden effects: changing globals or the input without saying so.
- Returning different kinds of things in different cases.
- Comments that repeat the code instead of explaining why.
Key takeaways
- A docstring (the first string in the function) documents it;
help(f)andf.__doc__show it. - Annotations (
x: int,-> str) are hints for people and tools; Python does not enforce them. doctestruns the>>>examples in docstrings and checks the results.- Good functions have one job, a clear name, few parameters, no hidden effects and a predictable return.
- Use guard clauses, raise
ValueErrororTypeErrorfor bad arguments, andassertonly for your own checks.
Practice
1. Add a one-line docstring to def double(n): return n * 2.
Show answer
def double(n):
"""Return n multiplied by two."""
return n * 2
2. What does def f(x: int) -> str: do if you call f("a")?
Show answer
Nothing special: Python does not check annotations while running. A tool such as mypy would warn about it before you run the program.
3. What does help(f) show for a function with a docstring?
Show answer
The function's name, its signature (with defaults and annotations) and the docstring.
4. Why is assert age >= 0 a poor way to check what a user typed?
Show answer
Assertions can be switched off when Python runs with -O, so the check might silently disappear. Raise a ValueError instead.
5. What makes a function "pure"?
Show answer
It depends only on its arguments and has no side effects: the same inputs always give the same output, and it changes nothing else.
6. Rewrite this with a guard clause: if x > 0: then return "ok" inside nested blocks, else: return "bad".
Show answer
def check(x):
if x <= 0:
return "bad"
return "ok"