Sub topic 10
Checking documentation against the code
This chapter assumes you can run pytest, read a Python traceback, and review a pull request. It also assumes you have already had an assistant draft a docstring or README, as in the previous chapters. Here you will check that the draft is true.
A generated docstring reads fluently whether it is right or wrong. The assistant predicts plausible text from the code you showed it, and it cannot run anything unless you give it a tool to do so. Reading the docs and nodding is a weak check. This chapter shows how to turn documentation claims into checks that a machine runs.
What can be wrong in generated documentation
Most documentation errors fall into a few categories. Knowing them tells you which check to use.
| Kind of error | Example | Best check |
|---|---|---|
| Wrong example output | Docs say `90.00`, code returns `90.0` | Doctest |
| Wrong behavior claim | Docs say percent of 0 raises, code accepts it | Test derived from the docs |
| Wrong structure | Docs describe a parameter that does not exist | Signature check |
| Missing behavior | An error path is never mentioned | Compare against the code's `raise` statements |
| Stale content | Docs describe an old function name | CI, run on every change |
A single review pass catches none of these reliably. Each needs its own mechanism, and the first three can be automated.
Run the examples with doctest
The doctest module in Python's standard library finds lines that start with >>> inside docstrings, runs them, and compares the printed result with the text on the next line. It is the cheapest way to check generated examples because the assistant's claims are executed against the real function.
Save this as pricing.py. It is the documented version of apply_discount from earlier chapters, with two error examples added.
def apply_discount(price: float, percent: float) -> float:
"""Return price reduced by percent, rounded to two decimals.
Args:
price: Original price. Must be non-negative.
percent: Discount from 0 to 100 inclusive.
Returns:
The discounted price rounded to two decimal places.
Raises:
ValueError: If price is negative or percent is outside 0-100.
Examples:
>>> apply_discount(100, 10)
90.0
>>> apply_discount(80, 25)
60.0
>>> apply_discount(50, 100)
0.0
>>> apply_discount(-1, 10)
Traceback (most recent call last):
...
ValueError: price must be non-negative
"""
if price < 0:
raise ValueError("price must be non-negative")
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return round(price * (1 - percent / 100), 2)Run it:
python -m doctest -v pricing.pyWith -v, doctest lists every example and ends with a summary of how many passed. Without -v, it prints nothing when everything passes, which is easy to misread as "nothing ran". Use -v the first time so you can confirm the examples were found.
Now suppose the assistant had written 90.00 as the expected output of the first example. Doctest compares text, not numbers, so it reports a failure:
**********************************************************************
File "pricing.py", line 14, in pricing.apply_discount
Failed example:
apply_discount(100, 10)
Expected:
90.00
Got:
90.0
**********************************************************************The failure message is what you paste back to the assistant. It contains the example, the claim, and the real behavior.
Doctest gotchas
- Float output. Doctest compares the printed
repr. Examples with results such as0.1 + 0.2print long digits. Pick inputs whose results are exact, or wrap the call inround, or use# doctest: +ELLIPSIS. - Silent skipping. A docstring with a typo such as
>>instead of>>>is not an example. Doctest ignores it and reports success. Check the count in verbose output. - Blank lines. A blank line ends the expected output. If an example prints a blank line, the docstring needs
<BLANKLINE>. - Tracebacks. Doctest checks only the exception type and message, not the stack lines. The
...line in the traceback header is how you write it. - Examples that depend on state. Examples that touch the network, the clock, or the filesystem are not stable. Ask the assistant to leave them out or mark them with
# doctest: +SKIP, and say so in the prompt.
To run doctests as part of the normal test suite, use pytest's built-in support:
pytest --doctest-modules pricing.pyCheck names and structure against the signature
Doctest verifies examples. It does not verify the Args: section. An assistant can document a parameter called discount_rate when the real name is percent, and every doctest still passes. A small test can compare the documented names with the real signature.
import inspect
import re
from pricing import apply_discount
def documented_params(func):
doc = inspect.getdoc(func) or ""
match = re.search(r"^Args:\n((?:[ ]+.*\n?)+)", doc, re.MULTILINE)
if not match:
return set()
return set(re.findall(r"^ {4}(\w+):", match.group(1), re.MULTILINE))
def test_documented_params_match_signature():
actual = set(inspect.signature(apply_discount).parameters)
assert documented_params(apply_discount) == actualinspect.getdoc removes the shared indentation, so parameter lines sit four spaces in under Args:. The regular expression collects lines of the form name: at that indentation and ignores wrapped continuation lines, which are indented further.
This helper is deliberately small and only fits Google-style docstrings. If you want it for a whole project, existing linters such as pydoclint (and darglint, which is no longer actively maintained) compare docstring sections with function signatures. They check structure, such as parameter names and whether a Raises: section exists. They do not check whether the sentences are true.
Check the other direction too. The code contains two raise statements and the docstring lists ValueError once. If an assistant adds a third error path in a later edit and never updates the docstring, the signature check will not notice. The next section covers that.
Turn prose claims into tests
Prose such as "Raises ValueError if percent is outside 0-100" is a claim about behavior. Verify it by writing a test from the claim, not from the code. This is the same discipline you used when reviewing tests: derive the expected result from the contract so the check is independent of the implementation.
import pytest
from pricing import apply_discount
@pytest.mark.parametrize(
"price, percent",
[
(10, -0.01),
(10, 100.01),
(-0.01, 50),
],
)
def test_documented_error_conditions_raise(price, percent):
with pytest.raises(ValueError):
apply_discount(price, percent)
@pytest.mark.parametrize("percent", [0, 100])
def test_documented_inclusive_bounds_are_accepted(percent):
apply_discount(10, percent)The second test targets a common documentation error. "From 0 to 100 inclusive" and "between 0 and 100" are ambiguous in prose, and an assistant may pick the exclusive reading. A test at the exact boundary settles which reading the code implements. If the code and the docs disagree, decide which one is the intended contract. Then fix the other. Do not let the assistant decide by rewriting whichever side is easier to change.
Doctest and these tests complement each other. Doctest checks what the examples show. These tests check what the sentences promise.
Checking a README
READMEs contain commands, install steps, and code samples that are easy to get wrong. The same principle applies: run them.
- Python samples in Markdown. Pytest can run
>>>examples inside a Markdown file withpytest --doctest-glob="*.md" README.md. Ask the assistant to write README samples in that format when they are short. - Longer samples. Copy the code block to a scratch file and run it in a clean virtual environment. A sample that works in your active environment can fail because it relies on a package you installed earlier and the README never mentions.
- Shell commands. Run every command on a fresh checkout. Check flags against
--helpoutput. Assistants often invent plausible options. - Version and install claims. Compare "requires Python 3.9+" with the
python_requiresorrequires-pythonfield in your project metadata, and with the syntax the code uses. - Links and file paths. Confirm that each referenced file exists. Assistants sometimes describe a
docs/folder or aconfig.yamlthat your repository does not have.
Use the assistant for the review step, with evidence
The assistant can still help, as long as its answer can be confirmed. Useful prompts give it both the code and the docs and ask for specific, checkable output:
Compare the docstring below with the function body.
List every statement in the docstring that the code does not support,
and every behavior in the code (return values, exceptions, defaults,
side effects) that the docstring does not mention.
For each item, quote the line of code or docstring you are relying on.
Do not rewrite anything yet.
<code and docstring here>The instruction to quote lines makes each finding easy to confirm. The instruction not to rewrite keeps the review separate from the fix. Treat the result as a list of leads, and verify each one yourself.
What these checks cannot tell you
- Intent. Doctest passes if the docs and the code agree, even when both are wrong. If a function should reject a percent of 0 and does not, a docstring that says it accepts 0 is consistent and incorrect.
- Missing context. Docs can be accurate and unhelpful. No tool flags a README that omits the one setup step everyone gets stuck on. Ask a teammate who has not seen the project to follow it.
- Drift over time. A check that passes today says nothing about next month. Keep doctests, signature checks, and README samples in the test run that executes on every pull request, so a code change that makes the docs false fails the build. The final chapter covers this setup.
Exercise
Exercise
A generated docstring for applydiscount lists the parameter `discountrate under Args, but the function's parameter is named percent`. All doctest examples in the docstring pass. Why did doctest not catch the error, and what check would?
Show answer
Doctest only runs the >>> examples and compares their output, so it never reads the Args section. The examples call the function positionally, so the wrong name in the prose does not affect them. A signature check catches it: compare the parameter names documented under Args with inspect.signature(apply_discount).parameters, either with a small test like test_documented_params_match_signature or with a docstring linter such as pydoclint.
Exercise
The docstring says "percent: Discount from 0 to 100 inclusive." Write two parametrized test cases that verify the word "inclusive" against the real function, and say what a failure would mean.
Show answer
Call apply_discount(10, 0) and apply_discount(10, 100) and assert that neither raises (the test in this chapter does this with @pytest.mark.parametrize("percent", [0, 100])). If either call raises ValueError, the code treats a boundary as invalid and the docs are wrong, or the code has a bug. Decide which one reflects the intended contract, then fix that side only.