Python foundations

Python Docstrings vs. Comments: What to Write Where

See which strings Python recognizes as docstrings, how help() displays them, and when a # comment belongs next to the code.

A Python docstring is a string literal at the start of a module, class, or function body. Use it to tell readers how to call the code and what to expect. A comment begins with # outside a string and can explain a decision next to the relevant line. You can inspect a recognized docstring with help() or __doc__.

def report_title(room):
    """Return a display title for a nonblank room name."""
    cleaned = room.strip()
    if not cleaned:
        raise ValueError("Room name must be nonblank")
    return f"Room report: {cleaned}"

assert report_title.__doc__.startswith("Return a display title")
assert report_title(" East ") == "Room report: East"

The first statement inside report_title is the docstring. A triple-quoted string placed after cleaned = room.strip() is an ordinary string expression and will not become the function’s docstring.

Document inputs, return values, and errors

A good function summary tells the caller what result to expect. Add details when the input units, empty result, errors, or side effects are unclear from the signature. “Return the elapsed time in seconds” is more useful than “calculate elapsed time.” “Return an empty list when no readings match” lets the caller use that result without guessing.

If zero is a meaningful result, document that in the public docstring. A local comment can explain why the implementation uses is None to detect missing input. That explanation belongs next to the check where a future reader might otherwise simplify it to if not value.

Keep comments focused on reasons and constraints

A comment like “increment the count” above count += 1 adds little. Explain which events count, why a boundary is exclusive, or why a branch keeps a seemingly special case. Someone reviewing a patch will then know why changing a single comparison could change a published result.

A useful comment also identifies assumptions that are external to the code. If an input parser assumes the upstream source already removed empty rows, say where that assumption comes from. When the upstream behavior changes, the comment gives the next maintainer an obvious place to look. Prefer a named constant or direct expression when it can make the same point on its own.

Separate documentation from disabled code

A string containing # can be legitimate data, such as "room #12". It does not become a comment. Repeated line comments are the ordinary way to write a multi-line comment in source. Large blocks of old code make a file harder to review, so rely on version history when you need to recover an abandoned approach.

For public APIs, use project conventions consistently. A short summary and a separate paragraph for return values or exceptions scale better than a long explanation pasted into every function. Docstring formatting conventions vary across tooling, so check the project's documentation build if it needs to expose particular fields.

Review documentation alongside the behavior

Run the actual example if the docstring promises what a call returns. Check any stated exception against the condition that raises it. When a change alters an accepted input, revise its description and its test together. A useful documentation review ends with a simple question: could a reader call this function correctly without opening the implementation?

Sources and further reading

Related reading

Browse Python foundations · Explore project tutorials

Search PythonProjects.org