How can a function docstring explain its contract without repeating its code?
Quick answer
Describe what callers need to know, not the steps the function takes. State the function’s purpose, any important input requirements, what it returns, and errors callers may need to handle. Skip details that are obvious from the signature or implementation. A useful test: could someone use the function correctly without reading its body?
The question, the details, the next step.
A practical checklist
State the function’s purpose in one short opening sentence.
Explain input constraints or meanings that are not clear from the signature.
Describe the return value, including important limits or shape.
Mention errors callers can encounter and may need to handle.
Note meaningful mutation or side effects.
Remove sentences that only narrate visible implementation steps.
A few more useful answers
Should every argument appear in the docstring?
Not necessarily. Document arguments when their meaning, constraints, or effect needs clarification; avoid restating information already obvious from a clear signature.
Do I need to describe how the function works internally?
Usually not in a caller-facing contract. Explain internal design only when it affects how someone should use, maintain, or rely on the function.
Should I list every error that might happen?
Focus on errors the function deliberately raises or that callers need to understand. Avoid implying that an error is part of the contract if the function does not define that behavior.
