Articles
Published · November 18, 2026

Docstrings vs Comments: What Each Is For, Following PEP 257

A comment is for people reading the source, and Python throws it away. A docstring is a string literal Python keeps as __doc__. Here is what each is for, with the PEP 257 rules.

Also in: Español中文हिन्दी

A comment explains the source to the person reading it, and Python discards it before the program runs. A docstring is a string literal that Python keeps and attaches to a module, class, or function, so tools and other code can read it. Use a docstring for what something does and how to call it. Use a comment for why the code is written the way it is.

Quick answer (one-paragraph TL;DR)

Both are documentation, but they don't have the same reader. A docstring talks to the person using a function: what it does, what it takes, what it returns. A comment talks to the person changing the function: why this odd line is here, what that workaround avoids. Here is one function with both:

def parse_port(value):
    """Return the port number in value as an int.

    Raise ValueError if value is not between 1 and 65535.
    """
    # int() accepts surrounding spaces, so no strip() is needed.
    port = int(value)
    if not 1 <= port <= 65535:
        raise ValueError("port out of range")
    return port

The docstring describes the contract. The # comment records a small piece of reasoning the code alone doesn't show.

How it actually works

What a docstring is, and where Python keeps it

PEP 257 defines it plainly: a docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. That docstring becomes the __doc__ special attribute of the object. Wikipedia's docstring entry states the key difference from a comment: a docstring is retained in the running program, while a comment is normally discarded by the language processor.

That is why this works in an interactive session:

>>> help(parse_port)
>>> print(parse_port.__doc__)

Both print the text you wrote. Tools such as Pydoc, Sphinx, and doctest also read docstring text.

Position matters. PEP 257 notes that string literals elsewhere in the code may act as documentation, but the bytecode compiler does not recognize them and they are not stored as __doc__. A string in the middle of a function body is just an unused expression, nothing more.

PEP 257 conventions you can apply today

PEP 257 describes itself as conventions, not laws or syntax, and adds that if you violate them, the worst you will get is some dirty looks. The rules are still worth following, because every Python reader expects them:

  • Quotes. Always use triple double quotes. Use r"""raw triple double quotes""" if the docstring contains backslashes.
  • One-liners are for really obvious cases. Keep the closing quotes on the same line, with no blank line before or after. Write a phrase ending in a period, as a command: "Return the pathname," not "Returns the pathname." Do not repeat the signature.
  • Multi-line docstrings. Start with a summary line, leave a blank line, then add the fuller description. The summary may be used by automatic indexing tools, so it should fit on one line. Put the closing quotes on their own line.
  • What to cover. For a function or method: its behavior, arguments, return values, side effects, exceptions raised, and restrictions on when it can be called. For a class: its behavior and its public methods and instance variables. For a module: the exported classes, exceptions, and functions, each with a one-line summary.
def is_blank(text):
    """Return True if text is empty or only whitespace."""


def load_config(path, defaults=None):
    """Read a settings file and return its values as a dict.

    Keys missing from the file are filled in from defaults.
    Raise FileNotFoundError if path does not exist.
    """

Comments in brief

A comment starts with # and a single space. A block comment sits above the code it describes, at the same indentation. An inline comment shares a line with a statement, separated by at least two spaces. Other languages use // or /* */ instead; see comment syntax across languages for the full list.

When to use it (and when to skip it)

Write a docstring for every public module, function, class, and method. That is the guidance in PEP 8, which points to PEP 257 for the details. Docstrings are not necessary for non-public methods, but PEP 8 says you should have a comment describing what the method does, placed after the def line.

Reach for a comment when the code needs a reason:

  • A workaround for a bug or quirk in another tool.
  • A value that looks arbitrary but is not.
  • A step that looks redundant but protects against a real edge case.

Skip the comment when it repeats the code. PEP 8 calls out comments that state the obvious as distracting. Its example of what not to write is x = x + 1 # Increment x, while x = x + 1 # Compensate for border is useful because it says why.

Two more cautions from PEP 8: comments that contradict the code are worse than no comments, so update them when the code changes, and docstrings and comments should wrap at 72 characters.

Keep the two jobs separate. A reasoning note in a docstring gets read by callers as part of the contract. And a bare string literal is no substitute for a comment: Python treats it as neither a comment nor a docstring.

Docstrings are one kind of documentation among several. The four kinds of documentation article explains where reference text like a docstring sits next to tutorials and how-to guides. And if you work in a format with no comment syntax at all, see formats with no comment syntax.

Finally, a project's own style guide wins over PEP 8 where the two disagree. PEP 257 describes the common default, not a mandate.

How Carets fits in

Docstrings and comments are plain text, and you often edit them in small, fast sessions: fixing a stale comment in a script on your iPad, or tidying a docstring in a snippet before you paste it elsewhere. Carets is a native notes and code editor for iPhone, iPad, and Mac, built for that kind of quick edit rather than as a web wrapper.

Syntax highlighting helps here. In a Python file, the triple-quoted docstring and the # comments render differently from the code around them, so you can see at a glance which text is a runtime docstring and which is a throwaway note. Carets keeps Markdown, plain text, and code in one editor, organized into files, projects, and tags, so a folder of Python snippets with their docstrings stays together and stays portable. Your files remain plain text.

Carets is a lightweight editor, not a full IDE. It won't run your tests or build your docs. For writing and polishing the text itself, it's quick and stays out of your way.

Download Carets for iPhone, iPad, and Mac on the App Store.

Frequently Asked Questions

Is a docstring just a comment?

No. A comment is discarded before the program runs. A docstring is a string literal that Python keeps as the object's __doc__ attribute, so help() and documentation tools can read it.

Do private functions need docstrings?

PEP 8 says docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does, placed after the def line.

Should a docstring use single or double quotes?

PEP 257 says to always use triple double quotes, and to use raw triple double quotes if the docstring contains backslashes.

Is a string in the middle of a function a docstring?

No. A docstring must be the first statement in the module, class, or function. String literals elsewhere are not stored as __doc__.