Code of the Day
IntermediateDocumentation that lasts

Docstrings and comments

Document the "why" in code — and let clear code document the "what".

FundamentalsIntermediate8 min read
Recommended first
By the end of this lesson you will be able to:
  • Write a docstring that describes a function's contract
  • Comment the why, not the what
  • Prefer self-documenting code to comments that drift

Documentation lives inside the code too. The goal is not "more comments" — it's that a reader (or an agent reading your code) can understand intent without running it. Done well, this is mostly clear code with a few well-placed words.

Docstrings: the contract, in place

A docstring documents what a function does, right where it's defined — and tools surface it via help() and IDE tooltips (the reading-a-reference skill, from the author's side). Describe the contract:

def sum_to(n):
    """Return the sum of all integers from 1 to n (inclusive).

    Args:
        n: a non-negative integer.
    Returns:
        The total as an int; 0 when n is 0.
    """

Say what it does, its inputs, what it returns, and any errors — the same parts a reader looks for. You're writing the reference entry you'd want to read.

Comment the why, not the what

Code already says what it does. A comment that restates it is noise that will drift out of date:

i = i + 1   # add one to i   ← useless

Comment the things code can't say — the reason, the trade-off, the gotcha:

# Retry once: the upstream API occasionally drops the first request after idle.
result = call_with_retry(url)

That comment captures knowledge no reader could recover from the code alone.

Prefer self-documenting code

The best comment is often a better name. Before explaining a tangle, see if you can make it not need explaining:

  • A clear function name beats a comment describing a block.
  • A well-named variable beats // x is the tax rate.
  • Small, well-decomposed functions read like prose (the decomposition lesson).

Every comment is a promise to keep it true. A comment that contradicts the code is worse than none — readers trust it and get burned. Write few, make them about why, and update them with the code they describe.

Where to go next

Code and docstrings explain the present. History needs documenting too. Next: writing a good message.

Finished reading? Mark it complete to track your progress.

On this page