How to Document Python Code: Docstrings and Reference Docs

Python has unusually good documentation habits built into the language. Docstrings are part of the runtime, type hints are part of the syntax, and a mature set of tools turns both into reference pages. Most Python projects still end up with documentation that is patchy, inconsistent or out of date, because the habits are optional and nothing checks them.

This guide covers what to write, in what format, and how to keep it current once the code starts changing.

Layer 1: Docstrings

A docstring is a string literal that is the first statement in a module, class, function or method. Python stores it on the object (func.__doc__), so help(), IDEs and documentation tools can all read it.

PEP 257 sets the basic conventions: triple double quotes, a one-line summary in the imperative mood ending with a period, then a blank line and the details if there are any.

def parse_duration(text: str) -> int:
    """Return the number of seconds in a duration like '1h30m'."""

For anything with parameters worth explaining, pick one structured style and use it everywhere. The two most common are Google style and NumPy style.

Google style is compact and reads well in short functions:

def fetch_user(user_id: int, include_deleted: bool = False) -> User:
    """Load a user by id.

    Args:
        user_id: The user's primary key.
        include_deleted: Also return users marked as deleted.

    Returns:
        The matching user.

    Raises:
        UserNotFound: If no user has that id.
    """

NumPy style uses underlined section headers and suits scientific code with many parameters:

def resample(series, rule, how="mean"):
    """Resample a time series to a new frequency.

    Parameters
    ----------
    series : pandas.Series
        The series to resample, indexed by datetime.
    rule : str
        Target frequency, such as "1H" or "1D".
    how : str, default "mean"
        Aggregation applied to each bucket.

    Returns
    -------
    pandas.Series
        The resampled series.
    """

Either is fine. Mixing them is not: tools parse them differently, and readers stop trusting the format.

What a good docstring says

Layer 2: Type hints

Type hints (PEP 484 and later) are documentation that a type checker can verify. Once a signature says def fetch_user(user_id: int) -> User, the docstring no longer needs to repeat the types, and tools like mypy or Pyright will tell you when a caller disagrees with them.

That is the most valuable property any documentation can have: it fails loudly when it is wrong. Lean on it. Put the types in the signature, and use the docstring for meaning.

Layer 3: Module and package docs

Every module benefits from a short docstring at the top saying what lives there and when to use it. Packages benefit from a README or an __init__.py docstring that explains how the pieces fit together. This is where a new contributor starts, and it is the documentation most often missing.

Layer 4: Generated reference pages

Once docstrings exist, a documentation site generator can pull them, together with your type hints, into browsable reference pages. Most of them understand both the Google and NumPy styles, which is one more reason to pick one style and keep to it.

These tools are excellent at presenting what you wrote. They cannot write it for you, and they cannot tell you that a docstring no longer matches the function beneath it.

Generating documentation for undocumented code

Most codebases have more undocumented code than anyone will ever go back and annotate by hand. That is where a documentation generator earns its place.

Writulos Scribe reads a Python file and writes structured markdown reference docs for it: an overview of what the module does and how it works, then a section for each function and class with a plain-English description, parameters with types, the return value and a usage example, plus dependencies and notes. It documents only what is actually in the code, so it does not invent behavior, and it uses your type hints and existing docstrings as part of what it reads.

It writes those docs as separate markdown files rather than editing your source, so nothing it produces ever lands in your code without review. You can paste a file into the app with no account to see the output, or run it on every push with the GitHub Action, which documents the .py files a change touches.

Keeping it current

Docstrings drift like any other documentation: a parameter is added, a default changes, and the docstring keeps describing the old function. A few habits slow that down.

  1. Keep types in signatures, so at least the types are checked by your type checker in CI.
  2. Test your examples. doctest runs the examples in your docstrings as tests, so an example that stops working fails the build.
  3. Make doc changes part of review, with a pull request template line that asks.
  4. Measure the rest. For generated reference docs, Scribe stamps each doc with the commit it was written from and counts the commits that have touched the source since, so you can see which docs are behind. On Pro and Business it can fail the pull request until they are current.

A checklist to start with

Good Python documentation is not one tool. It is a few layers, each catching what the others miss.