Sub topic 8
Generating docstrings from code
A docstring is a string literal at the start of a function, class, or module. Python tools such as help(), IDEs, and documentation generators read it. This chapter covers how to get an AI assistant to draft docstrings that state a function's contract, and how to catch the mistakes it tends to make.
This chapter assumes you can write and run pytest tests, read Python type hints, and review a diff in Git. It also assumes you have used an AI assistant and know that its output is a draft. Earlier chapters covered giving the assistant context. Here that context is applied to documentation.
What a docstring is for
A docstring should state the contract of a function. The contract covers what the function accepts, what it returns, and what it raises. It also covers any side effects. A reader should be able to call the function correctly without reading its body.
Assistants often write a different kind of text. They narrate the code, for example "Checks if price is less than zero, then checks percent, then multiplies." That tells the reader nothing the body doesn't already say. It also goes out of date as soon as the implementation changes.
| Narrates the code | States the contract |
|---|---|
| "Multiplies price by one minus percent over 100." | "Return price reduced by percent, rounded to two decimals." |
| "Raises an error in some cases." | "Raises ValueError if price is negative or percent is outside 0-100." |
| "Takes a float." | "price: Original price. Must be non-negative." |
When you review a generated docstring, ask whether it would still be true after a refactor that keeps the behavior the same. If it would, it describes the contract. If not, it describes the implementation.
Choose a style and say so
Python projects usually follow one of three docstring conventions.
- Google style uses
Args:,Returns:, andRaises:sections with indented descriptions. - NumPy style uses underlined section titles such as
ParametersandReturns. - reStructuredText (Sphinx) style uses field lists such as
:param price:and:raises ValueError:.
If you don't name a style, the assistant picks one, and it may mix styles within a file. Look at an existing docstring in your project and name that style in the prompt. If the project has no docstrings yet, choose one and write it into your contributing guide so later prompts can point to it.
Prompting for docstrings
Give the assistant the function, the style, and a list of what the docstring must and must not contain. The goal is to push it toward the contract and away from guessing.
Add a Google-style docstring to the function below.
Context:
- Python 3.11 project; docstrings follow Google style.
- Keep the first line as a one-sentence summary in the imperative mood.
Requirements:
- Document every parameter, the return value, and every exception the code raises.
- Add an Examples section with doctest-format examples (>>> lines).
- Use only the behavior visible in the code. If something is unclear, add a
line starting with "QUESTION:" instead of guessing.
- Do not change any code, only add or replace the docstring.
<code of apply_discount here>Three of these lines do most of the work:
- "Use only the behavior visible in the code" limits invention.
- The
QUESTION:instruction gives the assistant a place to put uncertainty. Without it, it fills gaps with plausible wording. - "Do not change any code" prevents silent edits to the function. Check the diff anyway.
A worked example
Start with the function from the running example. It has a short docstring that is accurate but incomplete.
def apply_discount(price: float, percent: float) -> float:
"""Return price reduced by percent, rounded to two decimals.
Raises ValueError if price is negative or percent is outside 0-100.
"""
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)After the prompt above, an assistant might produce this version.
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
"""
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)Every claim here can be checked against the code. The Args entries match the two guard clauses. The Raises section lists the one exception type the function raises. The summary line is unchanged from the original.
Where assistants go wrong
Generated docstrings fail in predictable ways. Check for each of these during review.
- Invented behavior. The assistant writes "Returns None if percent is zero" or "Logs a warning" because it sounds like what such a function would do. Compare every sentence with the code.
- Missing exceptions. The assistant documents the
raisestatements it sees in the function. It may miss exceptions raised by calls inside the function, such as aKeyErrorfrom a dictionary lookup or aTypeErrorfrom passing a string where a number belongs. - Wrong or vague types. Type hints say
float, but the docstring says "a number" or "an int". Make the docstring agree with the signature, or fix the signature. - Restating names. "price: The price." adds nothing. Ask for constraints and units: non-negative, in dollars, inclusive range.
- Overclaiming guarantees. "Always returns exactly two decimal places" is false for a float.
round(90.0, 2)returns90.0, which displays one decimal. Floats are also stored in binary, so a displayed value may differ slightly from the decimal you expect. - Drift on later edits. If you change the function later, the docstring does not update itself. Ask the assistant to update both in the same request, then review both.
Turn examples into a check with doctest
The Examples section is the most useful part of a generated docstring, because Python can run it. The standard library's doctest module finds lines that start with >>>, executes them, and compares the output with the lines that follow.
python -m doctest -v pricing.pyIf the assistant wrote 90.0 where the function returns 90, the run fails and shows the expected and actual output. This gives you evidence about the examples without relying on your own reading. It checks only the examples, so a wrong sentence in the Returns section still passes.
You can also document an error path. A doctest for an exception compares the traceback header and the exception line. The lines in between are replaced by ....
def apply_discount(price: float, percent: float) -> float:
"""Return price reduced by percent, rounded to two decimals.
Examples:
>>> apply_discount(100, 10)
90.0
>>> apply_discount(10, 101)
Traceback (most recent call last):
...
ValueError: percent must be between 0 and 100
"""
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)Some outputs are fragile as doctests. Floats that print many digits, dictionaries on older Python versions, memory addresses, and timestamps can all differ between runs. Pick example inputs that give stable output, such as the whole-number results above, or compare a value inside the example, for instance >>> apply_discount(19.99, 0) == 19.99 with the output True.
The review loop
The steps below form a short loop you can repeat for each function. The diagram shows it.
When something fails, feed the failure back to the assistant. Paste the doctest output, or quote the sentence that is wrong and say why. A specific correction works better than "try again".
Other cases
- Classes. Document the class purpose and its public attributes in the class docstring. Document constructor arguments in
__init__or in the class docstring, depending on your style. Ask the assistant not to document private helpers unless you want them documented. - Modules. A module docstring says what the module is for, in a few lines. Assistants tend to list every function in it. That list duplicates the code, so leave it out.
- Other languages. The same approach works for JSDoc, Javadoc, or Rust doc comments. Name the format in the prompt. The checks differ. Rust runs doc examples with
cargo test, while JSDoc has no built-in runner. - Inline comments. Generated comments often restate the line below them. Ask only for comments that explain why something is done, and delete the rest.
- Large files. Send a few functions at a time. Quality drops when a long file is documented in one request, and review becomes harder.
Exercises
Exercise
An assistant adds this line to the docstring of apply_discount: "Returns 0.0 when percent is 100 or price is 0, without rounding." Name two ways to check the claim, and say what each tells you.
Show answer
First, read the code. The function always calls round(price * (1 - percent / 100), 2), so rounding always happens, which contradicts "without rounding". Second, run the claim: add >>> apply_discount(50, 100) with the expected output 0.0 to the docstring and run python -m doctest. The example would pass, but it would not catch the "without rounding" part, which shows that doctest checks only the examples and not the prose. The sentence should be corrected or removed.
Exercise
You paste a function that reads a file and parses JSON. The generated docstring has a Raises section with only ValueError. What did the assistant likely miss, and how would you change the prompt to reduce this?
Show answer
It likely missed exceptions raised by the calls inside the function, such as FileNotFoundError or PermissionError from opening the file, and json.JSONDecodeError (a subclass of ValueError) from parsing. Change the prompt to ask for every exception that can propagate, including from called functions, and to put a QUESTION: line where it is unsure. Then check each call in the body against the Raises section.
Exercise
Write a Google-style Args entry for a parameter named timeout that is a float number of seconds and must be greater than zero. Why is this better than "timeout: The timeout"?
Show answer
"timeout: Maximum time to wait, in seconds. Must be greater than zero." It gives the unit and the constraint, which the reader cannot infer from the name. The short form repeats the name and leaves out the information a caller needs.