Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 13 of 15

Documentation

Documenting Python code: docstrings for modules, functions and classes, docstring styles, help() and inspect, doctest for examples that double as tests, README files, and generating reference documentation.

Beginner 10 min read·Lesson 291 of 306 in Python Programming

Learning objectives

  • Write useful docstrings
  • Read documentation with help() and inspect
  • Use doctest to keep examples correct

Definition

Documentation explains what code does and how to use it. In Python, docstrings — string literals at the start of a module, class or function — are the primary form; they are available at runtime through help() and __doc__.

Introduction

A good docstring answers the reader's first questions without making them read the code: what does it do, what does it take, what does it return, what can go wrong?

Why it matters

Documented code is easier to use, review and maintain. Docstrings power editor tooltips and generated documentation sites.

Detailed explanation

A docstring is a string literal (usually triple-quoted) as the first statement of a module, class or function.

Start with a one-line summary in the imperative ('Return the area of a rectangle.'), then a blank line and details: parameters, return value, exceptions, examples.

Common styles include Google style (Args:, Returns:, Raises:), NumPy style and reStructuredText; pick one per project.

help(obj) displays docstrings; obj.__doc__ and inspect.getdoc(obj) access them in code; inspect.signature shows parameters.

doctest runs examples written as interactive sessions (>>> lines) inside docstrings and checks their output, keeping examples correct.

Type hints complement docstrings by documenting types precisely.

A README explains the project as a whole: what it does, how to install and run it, and an example. Comments explain tricky lines; docstrings explain interfaces.

Tools such as Sphinx and MkDocs generate documentation websites from docstrings.

Syntax

Python
def area(width, height):
"""Return the area of a rectangle.
Args:
width: Width in metres (non-negative).
height: Height in metres (non-negative).
Returns:
The area in square metres.
"""
return width * height
  • One-line summary first.
  • Then arguments, returns, raises.
  • Visible via help().

Code examples

Reading docstrings

Python
import inspect
def area(width, height):
"""Return the area of a rectangle.
Both arguments must be non-negative numbers.
"""
return width * height
print(area.__doc__.splitlines()[0])
print(inspect.getdoc(area).splitlines()[-1])
Output
Return the area of a rectangle.
Both arguments must be non-negative numbers.

Examples that are tests

Python
import doctest
def square(n):
"""Return n squared.
>>> square(4)
16
>>> square(-3)
9
"""
return n * n
print(doctest.testmod())
Output
TestResults(failed=0, attempted=2)

More examples

Generating a mini reference

Python
import inspect
def convert(amount: float, rate: float = 83.5) -> float:
"""Convert US dollars to rupees."""
return round(amount * rate, 2)
def split_bill(total: float, people: int) -> float:
"""Split a bill evenly, rounded to 2 decimals."""
return round(total / people, 2)
for func in [convert, split_bill]:
print(f"{func.__name__}{inspect.signature(func)}: {inspect.getdoc(func)}")
Output
convert(amount: float, rate: float = 83.5) -> float: Convert US dollars to rupees.
split_bill(total: float, people: int) -> float: Split a bill evenly, rounded to 2 decimals.

Step-by-step explanation

  • inspect.signature turns parameters, defaults and type hints into readable text.
  • inspect.getdoc returns the cleaned-up docstring.
  • Documentation generators such as Sphinx do the same on a larger scale.

Expected output

Running “Generating a mini reference” prints exactly:

TextOutput
convert(amount: float, rate: float = 83.5) -> float: Convert US dollars to rupees.
split_bill(total: float, people: int) -> float: Split a bill evenly, rounded to 2 decimals.

Practical applications

  • Library documentation websites generated from docstrings.
  • Editor tooltips showing a function's docstring as you type.

Best practices

  • Give every public function, class and module a docstring.
  • Use one docstring style per project.
  • Keep examples correct with doctest.

Common mistakes

Docstrings that restate the name

Avoid

def get_user(id):
"""Gets the user."""

Prefer

def get_user(user_id):
"""Return the user with this id, or None if no such user exists."""

Explain behaviour and edge cases, not just the name.

Outdated documentation

Avoid

"""Returns a list.""" # the function now returns a dict

Prefer

Update docstrings with the code, or use doctest to catch drift.

Wrong documentation is worse than none.

Important notes

  • Comments start with #; docstrings are strings and become part of the object.

Key takeaways

  • Docstrings document modules, classes and functions.
  • help(), __doc__ and inspect read them.
  • doctest checks examples in docstrings.

Try it yourself

  1. 1
    Write Google-style docstrings for three functions from an earlier project.
  2. 2
    Add doctest examples to a function and run doctest.testmod().

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic