Documenting a Function with a Docstring

A docstring should tell a caller what the operation means, which inputs are valid, and what result or failure to expect.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Explain what the signature leaves open
  2. Choose a small example
  3. Write what a reader needs to call safely
  4. Choose examples that exercise a guarantee

Explain what the signature leaves open

For a function receiving a distance, the docstring can state meters, specify whether zero is allowed, and say whether the result is seconds. Use the normal signature for parameter names. Include units and rounding choices that types alone cannot express.

Choose a small example

A conversion output of 1.5 for 1500 milliseconds shows fractional seconds are preserved. If a different representation is required, update the example and its test together. See writing function contracts for recording side effects and ordinary failures too.[1][2]

Write what a reader needs to call safely

Suppose reading_at(index) gets a value by zero-based position. A docstring can say which collection is read, which positions are accepted, how missing readings are represented, and whether an out-of-range value raises. “Gets reading at index” repeats the name and leaves all four questions unresolved. A call using position zero with a missing reading demonstrates the difference between a successful read and an invalid position. See zero-based indexing for the boundary to make explicit.

Choose examples that exercise a guarantee

If the function accepts negative indexes, an example with index minus one teaches that policy. If negatives raise, the example can show the expected exception type. An example with a middle positive position confirms little about either boundary. Keep syntax examples runnable and avoid implying a precise error message unless callers are allowed to rely on it. Update the docstring and the tests in the same change when a function's public contract changes.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Execution Model ↩