Codectionary / Developer documentation / Python

Comments & Docstrings

A comment explains code to a reader and starts with # outside a string. A docstring is a string used as the first statement of a module, class or function; Python makes it available through __doc__ and tools such as help(). They serve different purposes.

How it works

Use a comment to explain a decision, assumption or surprising detail. A useful comment might say why a limit exists, rather than repeat that a variable is being incremented. Python ignores comment text during execution.

Docstrings describe the public contract: what the function does, which arguments it accepts, what it returns and which errors callers should expect. They must agree with the implementation. Triple quotes support multiple lines but do not automatically make an arbitrary string a docstring.

Inside a string, # is an ordinary character. Outside a string, a comment continues to the end of the physical line. Use your editor’s comment command to temporarily disable several lines rather than treating triple-quoted text as a general block-comment syntax.

Common mistakes and boundaries

A comment does not satisfy an otherwise empty code block. Use pass when a statement is required.

Do not leave credentials or private information in comments: comments remain in source control and can be distributed with the program. Remove obsolete commented-out code once it is no longer useful.

Try it yourself

Write a function that converts minutes to seconds. Add a one-line docstring that describes its input and result, and one comment explaining an assumption. Inspect its __doc__ attribute.

Syntax

# Explain a decision
"""Describe the module, class or function."""

Examples

Single-Line Comments

Explaining a line or block of code with #.

# Calculate the area of a circle
radius = 5
area = 3.14159 * radius ** 2  # pi * r^2
print(area)
  1. The first comment describes the calculation; the inline comment annotates the expression. Neither changes the result.
  2. Expected output: 78.53975

Function Docstrings

Documenting what a function does, its parameters, and its return value.

def add(a, b):
    """
    Add two numbers together.

    Args:
        a (int): The first number.
        b (int): The second number.

    Returns:
        int: The sum of a and b.
    """
    return a + b

print(add.__doc__)
  1. The first statement in add is its docstring. __doc__ contains its original line breaks and indentation; help() presents documentation more conveniently.
  2. Expected output: Add two numbers together. Args: a (int): The first number. b (int): The second number. Returns: int: The sum of a and b.

Commenting Out Code

Temporarily disabling a line of code while debugging.

total = 0
for i in range(10):
    total += i
    # print(f"Running total: {total}")  # disabled for now

print(total)
  1. The temporary diagnostic is disabled, but the accumulation still runs and produces the sum of 0 through 9.
  2. Expected output: 45

Best practices

  • Write comments that explain *why* the code does something, not *what* it does - the code itself should already show what
  • Add a docstring to every public function, class, and module so help() and documentation tools can describe them
  • Keep comments up to date - a comment that contradicts the code it describes is worse than no comment at all
  • Use triple-quoted strings for docstrings even on a single line ('''One-line summary.''') for consistency

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading