Python Documentation and Docstrings
What you will learn
- What a docstring is and where it goes
- One-line and multi-line docstrings, and the common styles
- How
help(),__doc__andpydocuse them - Comments: when they help and when they hurt
- Keeping examples true with
doctest - What a good README contains
- How docstrings and type hints work together
1. Why document?
Code tells the computer what to do; documentation tells people what it is for and how to use it, including your future self. Good documentation answers: What does this do? What does it take and return? What can go wrong? Can I see an example?
Python has a built-in convention for it: the docstring.
2. Docstrings
A docstring is a string literal placed as the first statement of a module, function, class or method. Python stores it in the object's __doc__ attribute, and tools (the help() function, editors, documentation generators) read it.
def clamp(x, low, high):
"""Limit x to the range low..high."""
return max(low, min(x, high))
print(clamp.__doc__)
help(clamp)
Limit x to the range low..high.
Help on function clamp in module docs1:
clamp(x, low, high)
Limit x to the range low..high.
(The module name docs1 is from the file used for the check.) A docstring is not a comment: it is real data attached to the object (lesson 11.8).
The two forms
One line, for simple things: a short sentence ending with a full stop, in the imperative ("Return ...", "Add ...", "Limit ..."), on one line with the quotes.
Multi-line: the first line is a summary like the above, then a blank line, then details:
def mean(values):
"""Return the arithmetic mean of a non-empty sequence of numbers.
Args:
values: A sequence of numbers (int or float).
Returns:
The mean as a float.
Raises:
ValueError: If ``values`` is empty.
"""
if not values:
raise ValueError("mean of empty sequence")
return sum(values) / len(values)
Use triple double quotes """ always (PEP 257 is the convention for docstrings).
Quick check: where must a docstring be placed to count as one?
As the first statement in the module, function, class or method body.
3. What to document, and where
| Object | What the docstring should say |
|---|---|
| module | what the file is for, perhaps its main functions; at the top of the file |
| function / method | what it does, its parameters, what it returns, errors it raises, side effects |
| class | what an object represents; its public attributes; how to create it |
__init__ |
often the class docstring covers it; document arguments in one of them |
Document the public parts: names without a leading underscore. Do not repeat what the code says; explain what the name cannot (units, allowed ranges, meaning of None, order of items, what happens at the edges).
class Account:
"""A simple bank account.
Attributes:
owner: The account holder's name.
balance: The current balance.
"""
def __init__(self, owner, balance=0):
"""Create an account for ``owner`` with an opening ``balance``."""
self.owner = owner
self.balance = balance
def deposit(self, amount):
"""Add ``amount`` to the balance and return the new balance."""
self.balance += amount
return self.balance
4. Docstring styles
Python does not insist on a layout for the details. Three styles are common; choose one per project and stay with it:
| Style | Looks like |
|---|---|
sections named Args:, Returns:, Raises: with indented lines (used above) |
|
| NumPy | sections with underlines: Parameters, ----------, Returns, ------- |
| reStructuredText (Sphinx) | field lists: :param x: ..., :returns: ..., :raises ValueError: ... |
Example of the same function in the reStructuredText style:
def clamp(x, low, high):
"""Limit x to the range low..high.
:param x: The value to limit.
:param low: The smallest allowed result.
:param high: The largest allowed result.
:returns: ``x``, or ``low`` or ``high`` if ``x`` is outside the range.
"""
The Google style is the most readable in plain text. If you use type hints (lesson 19.1), do not repeat the types in the docstring: the signature already shows width: int, and the two copies drift apart.
def shorten(text: str, width: int, placeholder: str = "...") -> str:
"""Cut ``text`` to at most ``width`` characters, ending with ``placeholder``."""
help(shorten) shows the signature with its hints together with the docstring:
shorten(text: str, width: int, placeholder: str = '...') -> str
Cut ``text`` to at most ``width`` characters, ending with ``placeholder``.
5. Reading documentation
| Tool | Use |
|---|---|
help(obj) |
show the documentation in the interpreter |
obj.__doc__ |
the raw text |
inspect.getdoc(obj) |
the text with the indentation cleaned up |
python -m pydoc name |
the same help from the terminal; python -m pydoc -b opens a browser version |
| editors | show the docstring on hover |
| Sphinx or MkDocs | build a full documentation website from docstrings and text files |
For a class, python -m pydoc docs1.Account printed:
Help on class Account in docs1:
docs1.Account = class Account(builtins.object)
| docs1.Account(owner, balance=0)
|
| A simple bank account.
|
| Attributes:
| owner: The account holder's name.
| balance: The current balance.
|
| Methods defined here:
|
| __init__(self, owner, balance=0)
| Create an account for ``owner`` with an opening ``balance``.
|
| deposit(self, amount)
| Add ``amount`` to the balance and return the new balance.
Your docstrings become the documentation of your own code, with no extra work.
6. Comments
A comment starts with # and is for people reading the source, not for users of the code.
| Good comments | Bad comments |
|---|---|
explain why: # retry once: the server sometimes drops the first call |
repeat what: # add 1 to i above i += 1 |
warn about traps: # order matters: validate before saving |
out-of-date text that disagrees with the code |
mark known gaps: # TODO: handle leap seconds |
commented-out old code (git remembers it) |
| cite a source or formula | long stories; use the commit message or documentation |
Prefer clear names and small functions to comments that explain unclear code. If a block needs a comment to be understood, consider extracting a function whose name says it. And keep comments in step with the code: a wrong comment is worse than none.
7. Examples that stay true: doctest
Documentation examples go out of date. The standard-library doctest module solves this: it finds examples written like an interactive session (>>> followed by the expected output) inside docstrings and runs them, comparing results. One example fails on purpose here:
def broken_double(x):
"""Double a number.
>>> broken_double(2)
5
"""
return x * 2
Running python -m doctest module.py prints nothing when all examples pass, and reports failures like this:
File "docs1.py", line 50, in docs1.broken_double
Failed example:
broken_double(2)
Expected:
5
Got:
4
***Test Failed*** 1 failure.
Doctests can also check exceptions (the traceback is written with ... for the middle lines):
>>> shorten("Hello", 2)
Traceback (most recent call last):
...
ValueError: width must be at least 3
python -m doctest -v module.pylists every example run (8 passed.for the module below).python -m pytest --doctest-modules module.pyruns them inside pytest (lesson 18.3); the three docstring groups of the module below gave3 passed.- Keep doctests short and about usage; use real tests (lessons 18.2 and 18.3) for edge cases and complex setups.
- Output must match exactly, including quotes and dictionary order; avoid examples whose output changes from run to run.
8. Project documentation
Documentation is more than docstrings. A project should have, at least, a README file (README.md, written in Markdown) at the top of the repository. A good README answers, in this order:
- What is it? One or two sentences.
- Why / who for? The problem it solves.
- Install / set up: the commands (lesson 16.6).
- Quick start: a minimal working example.
- Usage: the main features, or a link to fuller documentation.
- Development: how to run the tests and style checks (lessons 18.2, 19.3).
- Licence and contact: under what terms others may use it, and who maintains it.
Other useful files: CHANGELOG.md (what changed in each version), CONTRIBUTING.md (how to help), and a docs/ folder for longer guides. Write for a reader who has never seen the project; test your instructions on a clean environment.
Worked example: a documented module with tested examples
wordtools.py has a module docstring, Google-style function docstrings, type hints and doctests. The examples in the docstrings are executed, so they cannot lie.
"""Word tools: small helpers for counting and shortening text.
Example:
>>> import wordtools
>>> wordtools.count_words("the cat and the hat")
{'the': 2, 'cat': 1, 'and': 1, 'hat': 1}
"""
from collections import Counter
def count_words(text: str) -> dict[str, int]:
"""Count how often each word appears.
Words are separated by whitespace and compared in lower case.
Args:
text: The text to analyse.
Returns:
A dictionary mapping each word to its count, in order of first use.
Examples:
>>> count_words("the cat and the hat")
{'the': 2, 'cat': 1, 'and': 1, 'hat': 1}
>>> count_words("")
{}
>>> count_words("Go go GO")
{'go': 3}
"""
return dict(Counter(text.lower().split()))
def shorten(text: str, width: int, placeholder: str = "...") -> str:
"""Cut ``text`` to at most ``width`` characters, ending with ``placeholder``.
Args:
text: The text to shorten.
width: The maximum length of the result, placeholder included.
placeholder: What to put at the end of a shortened text.
Returns:
``text`` unchanged if it already fits, otherwise a shortened copy.
Raises:
ValueError: If ``width`` is smaller than the placeholder.
Examples:
>>> shorten("Hello, world", 20)
'Hello, world'
>>> shorten("Hello, world", 8)
'Hello...'
>>> shorten("Hello", 2)
Traceback (most recent call last):
...
ValueError: width must be at least 3
"""
if width < len(placeholder):
raise ValueError(f"width must be at least {len(placeholder)}")
if len(text) <= width:
return text
return text[: width - len(placeholder)] + placeholder
Running the examples:
$ python -m doctest -v wordtools.py
...
3 tests in wordtools.count_words
3 tests in wordtools.shorten
8 tests in 3 items.
8 passed.
Test passed.
$ python -m pytest --doctest-modules wordtools.py -q
... [100%]
3 passed in 0.08s
| Feature | Where |
|---|---|
| module docstring with an example | top of the file; it counts as one doctest item |
| summary line, then details | both functions |
Args, Returns, Raises |
Google style sections; types come from the hints, not repeated in the text |
| examples as tests | 8 examples in 3 documented items, all passing |
| the error example | shows the exact exception and message |
The text samples are made up. In a bigger project the same docstrings could feed an automatically built documentation website.
Common mistakes
- No docstrings on public functions and classes.
- Docstrings that repeat the name ("Gets the name.") instead of adding information.
- Repeating type hints in the docstring, so they disagree.
- Comments that restate the code, or lie.
- Commented-out code left in files.
- Examples that were never run, and no longer work.
- A README that does not say how to install or run the project.
- Mixing docstring styles in one project.
Key takeaways
- A docstring is the first statement of a module, function, class or method; Python stores it in
__doc__, andhelp(),pydocand editors show it. - Start with a one-line imperative summary, a blank line, then details (
Args,Returns,Raisesin the Google style). - Do not repeat what type hints already say.
- Comments explain why, not what; prefer clear names.
doctestruns the>>>examples in docstrings so documentation stays correct.- A README says what the project is, how to install it, a quick start, how to test it, and the licence.
Practice
1. Write a one-line docstring for a function area(w, h).
Show answer
def area(w, h):
"""Return the area of a rectangle with width w and height h."""
return w * h
2. How do you view a function's docstring in a terminal?
Show answer
help(function) in the interpreter, print(function.__doc__), or python -m pydoc module.function.
3. Why not write x: int again in the docstring when the signature has x: int?
Show answer
The two copies can drift apart and disagree; the signature (checked by mypy) is the single source of truth.
4. Which is the better comment: # increase count or # the API counts from zero, so add 1?
Show answer
The second: it explains why, which the code cannot show.
5. What does python -m doctest module.py do?
Show answer
It finds >>> examples in the docstrings of the module, runs them, and reports any whose output differs from what is written.
6. Name four things a README should contain.
Show answer
What the project is, how to install it, a quick-start example, how to run the tests, and the licence (and contact).