ZetCode

Python comments and docstrings

last modified November 29, 2026 Python 3.15

In this article we show how to write comments and docstrings in Python.

Python has two ways to document code. A comment starts with # and is meant for people reading the source code; the interpreter ignores it. A docstring is a string literal written as the first statement of a function, class, or module. It is kept at run time and describes how to use the object. The rules for writing docstrings are described in PEP 257.

Comments

A comment starts with the hash character and extends to the end of the line. It can occupy a whole line or follow code on the same line.

comments.py
# Convert a temperature reading from Fahrenheit to Celsius.
# The sensor reports whole degrees only.

fahrenheit = 98

celsius = (fahrenheit - 32) * 5 / 9   # exact formula, no rounding here
print(f'{celsius:.1f} °C')   # one decimal place is enough for display

The two full-line comments at the top describe the purpose of the program. The inline comments follow the code after at least two spaces, as PEP 8 recommends. Python has no special syntax for multi-line comments; a longer comment is a block of consecutive lines, each starting with #. How the tokenizer treats comments is shown in Python lexical structure.

$ python comments.py
36.7 °C

What a comment should say

The code itself shows what is done. A good comment explains what the code cannot: why it is written this way, what assumption it relies on, or what would break if it changed.

why_comments.py
items = 7
per_page = 3

# Bad: repeats what the code says.
# Add per_page minus one to items and divide by per_page.
pages = (items + per_page - 1) // per_page

# Good: explains why the code looks this way.
# Integer ceiling division; float division with math.ceil
# loses precision for very large item counts.
pages = (items + per_page - 1) // per_page

print(pages)

Both statements compute the number of pages needed for seven items when three fit on a page. The first comment only repeats the arithmetic in words and adds nothing. The second names the technique and tells the reader why the simpler-looking float version was not used. Comments must be updated together with the code; an outdated comment is worse than no comment.

$ python why_comments.py
3

Strings are not comments

Triple-quoted strings are sometimes used as multi-line comments. This is a risky habit: a string is an expression, and in some places it changes the meaning of the code.

string_not_comment.py
colors = [
    'red',
    'green'
    """ 'blue' was removed, see issue 42 """
]

print(len(colors))
print(colors)

The author tried to comment out 'blue' with a triple-quoted string. Because 'green' has no trailing comma, Python concatenates the two adjacent string literals into one element. The list has two items instead of one, and no error is reported. Use # for all comments.

$ python string_not_comment.py
2
['red', "green 'blue' was removed, see issue 42 "]

A first docstring

A docstring is the first statement in the body of a function. It is stored in the __doc__ attribute of the function.

first_docstring.py
def area(width, height):
    """Return the area of a rectangle."""
    return width * height


print(area(4, 5))
print(area.__doc__)

By convention, docstrings use triple double quotes, even when they fit on one line. A one-line docstring is a phrase ending with a period. PEP 257 recommends the imperative form, Return the area, rather than a description such as Returns the area. The docstring does not repeat the parameter names; they are visible in the signature.

$ python first_docstring.py
20
Return the area of a rectangle.

Multi-line docstrings

A longer docstring has a summary line, a blank line, and a more detailed description. The closing quotes go on a line of their own.

multiline_docstring.py
def bmi(weight, height):
    """Return the body mass index.

    The weight is given in kilograms and the height in metres.
    The result is not rounded.
    """
    return weight / height ** 2


print(repr(bmi.__doc__))
print()
print(bmi.__doc__)

The summary line must fit on one line, because tools show it alone in overviews. Since Python 3.13, the compiler removes the common leading indentation from docstrings, so __doc__ contains the text without the four spaces of the function body. The repr output shows the blank line after the summary and the trailing newline before the closing quotes.

$ python multiline_docstring.py
'Return the body mass index.\n\nThe weight is given in kilograms and the height in metres.\nThe result is not rounded.\n'

Return the body mass index.

The weight is given in kilograms and the height in metres.
The result is not rounded.

The help function

The built-in help function displays the documentation of an object. In an interactive session, it opens a pager; when the output is redirected, it prints the text.

help_function.py
def bmi(weight, height):
    """Return the body mass index.

    The weight is given in kilograms and the height in metres.
    The result is not rounded.
    """
    return weight / height ** 2


help(bmi)

The output starts with the name of the module where the function is defined, then the signature, and then the indented docstring. Editors and IDEs show the same text in tooltips when we type the function name.

$ python help_function.py
Help on function bmi in module __main__:

bmi(weight, height)
    Return the body mass index.

    The weight is given in kilograms and the height in metres.
    The result is not rounded.

What is not a docstring

Only a plain string literal written as the very first statement becomes a docstring. Comments and strings in other places are not stored.

not_docstring.py
UNIT = 'kg'


def no_doc():
    # A comment is not a docstring.
    return 1


def late_doc():
    x = 1
    """Not the first statement, so not a docstring."""
    return x


def fstring_doc():
    f"""Weight in {UNIT}."""
    return 2


print(no_doc.__doc__)
print(late_doc.__doc__)
print(fstring_doc.__doc__)

The first function has only a comment, which is discarded by the tokenizer. In the second function, the string comes after an assignment, so it is an ordinary expression statement that does nothing. In the third, the f-string is evaluated at run time, so it cannot be a docstring. All three functions have None in __doc__.

$ python not_docstring.py
None
None
None

Module docstrings

A module docstring is the first statement in a file, placed before the imports. It describes the contents of the module as a whole.

shapes.py
"""Functions for simple plane shapes.

All lengths are in centimetres and all areas in square
centimetres.
"""

import math


def circle_area(radius):
    """Return the area of a circle with the given radius."""
    return math.pi * radius ** 2


def square_area(side):
    """Return the area of a square."""
    return side * side

The module has a docstring and two documented functions. The pydoc tool, which is part of the standard library, imports the file and builds a page from all its docstrings. The summary line of the module appears next to its name, and the rest of the text goes into the DESCRIPTION section.

$ python -m pydoc ./shapes.py
Help on module shapes:

NAME
    shapes - Functions for simple plane shapes.

DESCRIPTION
    All lengths are in centimetres and all areas in square
    centimetres.

FUNCTIONS
    circle_area(radius)
        Return the area of a circle with the given radius.

    square_area(side)
        Return the area of a square.

FILE
    /home/user/comments-docstrings/shapes.py

Class and method docstrings

A class docstring is the first statement of the class body. Each method has its own docstring, written the same way as for functions.

class_docstring.py
class Account:
    """A bank account with a balance in cents.

    Amounts are stored as integers to avoid float rounding.
    """

    def __init__(self, owner, balance=0):
        """Create an account for owner with an initial balance."""
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        """Add amount, in cents, to the balance."""
        self.balance += amount


print(Account.__doc__.splitlines()[0])
print(Account.deposit.__doc__)
help(Account)

The class docstring describes what an object of the class represents; the docstring of __init__ describes the arguments of the constructor. The output of help collects all these docstrings. The __dict__ and __weakref__ entries are generated by Python for every ordinary class.

$ python class_docstring.py
A bank account with a balance in cents.
Add amount, in cents, to the balance.
Help on class Account in module __main__:

class Account(builtins.object)
 |  Account(owner, balance=0)
 |
 |  A bank account with a balance in cents.
 |
 |  Amounts are stored as integers to avoid float rounding.
 |
 |  Methods defined here:
 |
 |  __init__(self, owner, balance=0)
 |      Create an account for owner with an initial balance.
 |
 |  deposit(self, amount)
 |      Add amount, in cents, to the balance.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object

Google style

PEP 257 does not prescribe how to describe parameters and return values. Several conventions exist. The Google style uses short headings such as Args and Returns followed by indented entries.

google_style.py
def split_bill(total, people, tip=0.1):
    """Split a restaurant bill between people.

    Args:
        total: The bill without tip, in euros.
        people: The number of people paying.
        tip: The tip as a fraction of the total.

    Returns:
        The amount each person pays, rounded to cents.

    Example:
        >>> split_bill(84.0, 4)
        23.1
    """
    return round(total * (1 + tip) / people, 2)


print(split_bill(84.0, 4))

Each argument is listed with a short description. The Example section shows a call and its result in the form of an interactive session. This style is easy to read as plain text, and the Sphinx documentation generator can process it with its napoleon extension. The NumPy style, common in scientific packages, is similar but underlines the section headings with dashes.

$ python google_style.py
23.1

reStructuredText style

The default format of the Sphinx documentation generator is reStructuredText. Parameters are described with field lists such as :param name:.

rest_style.py
def split_bill(total, people, tip=0.1):
    """Split a restaurant bill between people.

    :param total: The bill without tip, in euros.
    :param people: The number of people paying.
    :param tip: The tip as a fraction of the total.
    :returns: The amount each person pays, rounded to cents.
    :rtype: float
    """
    return round(total * (1 + tip) / people, 2)


print(split_bill(84.0, 4))

The function is the same as in the previous example; only the docstring format differs. The :rtype: field gives the type of the return value. Field lists are compact but harder to read in the source. Which style to use matters less than using one style consistently throughout a project.

$ python rest_style.py
23.1

Testing examples with doctest

A docstring can contain examples written as an interactive session. The doctest module runs these examples and checks that the output matches.

doctest_example.py
def initials(name):
    """Return the initials of a full name.

    >>> initials('Ada Lovelace')
    'A.L.'
    >>> initials('  grace   brewster hopper ')
    'G.B.H.'
    >>> initials('')
    ''
    """
    result = ''
    for word in name.split():
        result += word[0].upper() + '.'
    return result

Each line starting with >>> is executed, and the following line is the expected result. Without the -v option, doctest prints nothing when all examples pass. With it, every example is reported. The examples document the edge cases, such as extra spaces and an empty name, and they cannot get out of date without the test failing.

$ python -m doctest -v doctest_example.py
Trying:
    initials('Ada Lovelace')
Expecting:
    'A.L.'
ok
Trying:
    initials('  grace   brewster hopper ')
Expecting:
    'G.B.H.'
ok
Trying:
    initials('')
Expecting:
    ''
ok
1 item had no tests:
    doctest_example
1 item passed all tests:
   3 tests in doctest_example.initials
3 tests in 2 items.
3 passed.
Test passed.

Removing docstrings

The -OO option of the interpreter removes docstrings from the compiled code to save memory. Programs must not depend on __doc__ for their behaviour.

stripped.py
def area(width, height):
    """Return the area of a rectangle."""
    return width * height


print(area.__doc__)
print(__debug__)

With -OO, the docstring is gone and __doc__ is None. The option also removes assert statements and sets __debug__ to False. A normal run keeps the docstring.

$ python -OO stripped.py
None
False
$ python stripped.py
Return the area of a rectangle.
True

Source

PEP 257 – Docstring conventions, PEP 8 – Comments, pydoc – Documentation generator, doctest – Test interactive Python examples, Google Python style guide – Comments and docstrings

In this article we have written comments that explain why, avoided strings as comments, and documented functions, modules, and classes with docstrings. We have displayed them with help and pydoc, compared the Google and reStructuredText styles, tested examples with doctest, and removed docstrings with -OO. See also Python lexical structure, Python introspection, and Python functions.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.