Sub topic 8
Generating docstrings from code
This chapter assumes you can read Python, run pytest and python -m doctest, and have already written a prompt that supplies context, as covered earlier in this tutorial.
What a docstring should hold
A docstring is a string at the top of a function that describes its contract. The contract is what callers can rely on: inputs, outputs, errors, and side effects. An assistant is good at turning code into prose. It is weaker at knowing which facts matter to callers, so you decide what the docstring must state.
The running example is apply_discount. Its first docstring is a short summary that already names the two error conditions:
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)Prompting for a docstring
Name the style, the sections, and the limits. Without them, assistants default to a generic format and tend to restate the code line by line.
Add a Google-style docstring to the function below.
Requirements:
- Sections: summary line, Args, Returns, Raises, Examples.
- Describe behavior visible in the code only. Do not guess at
behavior you cannot see, and mark anything unclear with TODO.
- Examples must be doctest-compatible (>>> prompts, exact output).
- Do not change the function body or signature.
<code of apply_discount here>The instruction to mark unclear behavior with TODO gives the assistant a safe alternative to inventing an answer.
A reviewed result
This is the kind of output you should expect, with an Examples section that the interpreter can check:
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)Run python -m doctest -v pricing.py. Each example is executed and compared with the printed output, so a wrong example fails instead of misleading a reader.
Common errors in generated docstrings
- Restating the code. "Checks if price is less than zero" says nothing the code does not. Ask for the reason or the rule instead.
- Wrong or missing exceptions. Compare the
Raisessection with everyraisestatement, and with exceptions raised by the functions you call. - Invented guarantees. A docstring that says "rounds half up" is wrong here. Python's
rounduses round-half-to-even on the float's binary value, soround(2.675, 2)returns2.67. - Drift. A docstring is accurate on the day you generate it. After the code changes, it can become false without any test failing, unless doctest runs in your checks.
Review checklist
- Every parameter in the signature appears in
Args, with constraints stated. Returnsmatches the type hint and any rounding or format rule.- Every
raisein the code appears inRaises. - Each example passes under
python -m doctest. - No sentence describes behavior you cannot point to in the code.
Exercise
An assistant adds the line "Percent may be given as a fraction such as 0.1 for 10 percent" to the apply_discount docstring. Is it accurate, and how would you check?
Show answer
It is inaccurate. The code computes price * (1 - percent / 100), so 0.1 means 0.1 percent, not 10 percent. Check by adding the example ">>> apply_discount(100, 0.1)" and running python -m doctest. It returns 99.9, not 90.0, which contradicts the claim. Then remove the sentence or correct it.