Python Docstring Format

Version 1.0

How Plain Text Office LLC writes docstrings in its Python code. Every Python app we build follows this format.

Why we write docstrings this way

Our code is read by people and by AI coding agents. Both need to know what a function promises before they change it. A good docstring explains intent, rules, side effects, and anything surprising. It does not repeat what the function name, type hints, or code already say.

When rules pull in different directions, apply them in this order:

PriorityFocusQuestion to ask
1Summary lineWhat should the caller understand first?
2DetailsWhat rule or behavior is not obvious?
3LayoutAre the blank line, bullets, and wrapping right?
4CoverageDoes this code need a docstring at all?

The basic shape

Every docstring has:

  1. A one-line summary.
  2. A blank line.
  3. Details, when more explanation helps.
def example_function(arg: str) -> bool:
    """Return whether the argument is valid.

    - Explain important assumptions and domain rules.
    - Document caller-visible side effects or error behavior.
    - Clarify non-obvious return behavior or edge cases.
    """

A summary line alone is fine when nothing more needs saying:

def normalize_name(value: str) -> str:
    """Return a normalized display name."""

The summary line

The first line says what the code does.

  • Keep it to one line. Never wrap it.
  • End it with a period.
  • Start with a verb in the imperative (“Parse”, “Return”) when you can.
  • Do not repeat the function, class, or module name.
  • Do not start with “This function…” or “This class…”.
  • Leave out implementation details unless they affect the caller.
  • Describe what it means, not how it works.

Good:

"""Parse a todo.txt line into a task model."""

Bad:

"""This function parses a todo.txt line into a task model."""

Bad:

"""parse_todo_line parses a todo.txt line."""

Length

Aim for 72 characters or fewer. The line may run up to the project’s line limit when it must, but it never wraps. If it is too long, shorten it and move the rest into the details.

Bad:

"""Parse a todo.txt line into a normalized task model while validating project, context, priority, and recurrence metadata."""

Better:

"""Parse a todo.txt line into a task model.

- Validates project, context, priority, and recurrence metadata before
  returning the normalized domain object.
"""

The blank line

Put a blank line after the summary whenever details follow.

Good:

def load_tasks(path: Path) -> list[Task]:
    """Load task records from disk.

    - The input file must contain one JSON object per line.
    - Invalid records are skipped and reported through the returned load result.
    """

Bad:

def load_tasks(path: Path) -> list[Task]:
    """Load task records from disk.
    The input file must contain one JSON object per line.
    """

The details

Use the details to explain what the signature does not show:

  • Domain rules
  • Important assumptions
  • What inputs are expected
  • What is returned, and when
  • What errors are raised
  • Side effects
  • Boundary decisions
  • Edge cases that are not obvious
  • How data is transformed
  • How data is saved or serialized

Do not repeat the type hints.

Good:

def complete_task(task: Task, completed_at: date) -> Task:
    """Return a completed copy of the task.

    - Completion does not mutate the original task.
    - The returned task keeps the original creation metadata.
    - The returned task records the supplied completion date.
    """

Bad:

def complete_task(task: Task, completed_at: date) -> Task:
    """Complete a task.

    Takes a task and a completed_at date. Returns a task.
    """

Line length

Wrap details at 88 characters, or at the project formatter’s limit if it uses a different one. Keep paragraphs short, one idea each. Code examples inside a docstring may run longer when wrapping would make them harder to read.

Bullets or prose

Use - bullets when the details hold several separate ideas: rules, modes, file formats, side effects, error cases, or constraints. Bullets make each one easy to find.

Use a paragraph when the details explain one continuous idea. Do not use * for bullets.

Good as prose:

def validate_task(task: Task) -> None:
    """Validate a task before persistence.

    A task is valid when it has user-visible text and belongs to exactly one
    recurrence period. Completion metadata is optional for active tasks.
    """

Good as bullets:

def validate_task(task: Task) -> None:
    """Validate a task before persistence.

    Validation enforces these domain rules:

    - The task text must not be empty.
    - The recurrence period must be one of the supported period values.
    - A completed task must include a completion timestamp.

    Raises ValueError when any rule fails.
    """

What needs a docstring

These always need a docstring:

  • Public modules, classes, functions, and methods
  • Internal helpers that do meaningful work
  • Internal helpers called by another function in the same module

A function or method needs one if any of these is true:

  • Its name does not start with _.
  • Another module imports it.
  • It is part of a domain API.
  • Orchestration code, adapters, or tests call it.
  • Another function in the same module calls it.
  • It holds domain, validation, or transformation logic.
  • It branches in ways that are not obvious.
  • It does I/O, logging, mutation, or talks to an outside system.

A private helper may skip its docstring only when all of these are true:

  • It is used in exactly one place.
  • It is very small.
  • It has no domain rule, validation rule, side effect, or meaningful branching.
  • Its name, parameters, and return type make its behavior obvious.

Internal helpers

A leading underscore marks a helper as internal to its module. It means “not part of the public API.” It does not mean “no docstring needed.” Document a helper when its behavior affects the correctness or readability of the function that calls it.

Good:

def build_export_payload(tasks: Sequence[Task]) -> list[dict[str, object]]:
    """Build serializable task records for export.

    - Each task is converted into the external JSON shape used by the export
      adapter.
    - Internal-only fields are intentionally omitted.
    """
    return [_task_to_export_record(task) for task in tasks]


def _task_to_export_record(task: Task) -> dict[str, object]:
    """Convert one task into its external export record.

    - User-authored fields are preserved.
    - Runtime-only state, such as cached period calculations, is excluded.
    """
    ...

Bad, because the helper that does the real work is undocumented:

def build_export_payload(tasks: Sequence[Task]) -> list[dict[str, object]]:
    """Build serializable task records for export."""
    return [_task_to_export_record(task) for task in tasks]


def _task_to_export_record(task: Task) -> dict[str, object]:
    ...

What counts as public

Code is public if any of these is true:

  • Its name does not start with _.
  • Another module imports it.
  • It is listed in __all__.
  • Orchestration code, adapters, or tests call it.
  • It represents a domain operation.
  • It is meant to be used outside the module that defines it.

A public docstring tells callers what they need to know, not how the code works inside.

What to explain

Domain meaning first

Explain what the code means in the problem it solves before how it computes the answer.

Good:

def active_recurrence_window(task: Task, today: date) -> DateRange:
    """Return the task's active recurrence window.

    - The recurrence window represents the period in which the task is expected
      to be completed.
    - The window is guidance-oriented and does not imply a strict due date.
    """

Bad:

def active_recurrence_window(task: Task, today: date) -> DateRange:
    """Calculate a date range using datetime operations."""

Side effects

Always mention side effects: reading or writing files, creating folders, changing inputs or global state, logging, printing, network requests, calls to outside systems, database writes, and changes to environment variables.

def write_tasks(path: Path, tasks: Sequence[Task]) -> None:
    """Write tasks to a JSON file.

    - The target file is overwritten.
    - Parent directories must already exist.
    """

Errors

List an exception only when callers are expected to handle it.

def parse_task_id(raw_value: str) -> TaskId:
    """Parse a task identifier from a string.

    - Raises ValueError when the value is empty.
    - Raises ValueError when the value does not match the task ID format.
    """

Do not list every low-level exception that could possibly occur.

Return values

Explain the return value when the name and type hint do not.

Good:

def find_task(tasks: Sequence[Task], task_id: TaskId) -> Task | None:
    """Return the task with the matching ID.

    Returns None when no task has the requested ID.
    """

Bad:

def find_task(tasks: Sequence[Task], task_id: TaskId) -> Task | None:
    """Find a task.

    Returns a Task or None.
    """

Classes and modules

A class docstring says what the class represents. Include the domain concept, rules that always hold, whether instances can change, and any lifecycle rules that are not obvious.

@dataclass(frozen=True)
class Task:
    """Represent a user-authored task.

    - Tasks are immutable domain objects.
    - State changes, such as completion, should return a new Task instance
      instead of mutating the existing one.
    """

A module docstring says what the module is responsible for. Keep it short.

"""Parse and serialize todo.txt task records.

- Owns conversion between external todo.txt lines and internal Task domain
  models.
- Does not perform filesystem I/O.
"""

What to leave out

  • Long accounts of how the code works
  • Change history and TODO notes
  • Type hints restated in words
  • The function name repeated
  • Line-by-line descriptions of obvious code
  • Promises the code does not enforce
  • Details about callers that do not affect this function

Bad:

def normalize_text(value: str) -> str:
    """normalize_text takes a string value and returns a string value.

    First it calls strip, then it replaces some spaces, then it returns the
    result.
    """

Better:

def normalize_text(value: str) -> str:
    """Return normalized task text.

    - Leading and trailing whitespace is removed.
    - Internal whitespace is collapsed so equivalent user input produces stable
      task text.
    """

Using this with AI coding agents

Each of our repositories gives this format to the AI agents that work on it. When they write or change Python code, agents:

  • Add docstrings to new public code and to meaningful internal helpers.
  • Use the summary line, blank line, and details shape, with the summary on one line.
  • Use - bullets for separate ideas and prose for one continuous idea.
  • Document rules, side effects, return values, and errors, not type hints or internal mechanics.
  • Update a docstring whenever the behavior it describes changes.
  • Keep a useful docstring even when the function is private.

Version history

VersionStatusChanges
1.0In useFirst public version