How to Do Multi-line Documentation in Python

What you’ll build or solve

You’ll write clear multi-line documentation in Python using docstrings for modules, functions, classes, and methods.

When this approach works best

This approach works best when you need to:

  • Explain what a function or class does, what inputs it expects, and what it returns.
  • Document a module so new teammates understand what the file is for.
  • Add longer notes about constraints, edge cases, or usage examples without cluttering the code.

Avoid this approach when:

  • You only need a short inline note. A single # comment is enough.
  • You want to explain why you changed something. Use commit messages and code review notes instead.

Prerequisites

  • Python 3 installed
  • You can edit a .py file in a code editor
  • You know what a function and a class look like

Step-by-step instructions

1) Write a module docstring at the top of the file

Place a triple-quoted string as the first thing in the file. Keep it focused on purpose and usage.

"""
Utilities for cleaning user input.

This module normalizes text fields like emails and usernames
before saving them to the database.
"""

What to look for:

The module docstring must come before imports and other code to be treated as the module docstring.


2) Write a function docstring as the first statement

Put the docstring right after def ...: and before any code. Describe behavior, inputs, and return value.

defnormalize_email(email):
"""
    Normalize an email address for storage.

    Strips leading and trailing whitespace and lowercases the result.
    Returns the normalized email as a string.
    """
returnemail.strip().lower()

Keep the first line short and clear. Add details in the following lines.


3) Write a class docstring to describe intent and constraints

Use the class docstring to explain what the object represents and how it should be used.

classRateLimiter:
"""
    Simple in-memory rate limiter.

    Tracks requests per key for the lifetime of the process.
    Use a shared store if you need consistency across servers.
    """
pass

Focus on purpose, lifecycle, and limitations.


4) Add method docstrings for non-obvious behavior

Document methods that have side effects, state changes, or important rules.

classCart:
"""
    Shopping cart that stores items in memory.
    """

defadd(self,sku,qty=1):
"""
        Add an item to the cart.

        sku: string product identifier
        qty: integer quantity to add (default 1)
        """
        ...

What to look for:

Keep method docstrings short if the class docstring already explains the broader context.


5) Choose a docstring style and stay consistent

Docstrings work best when your team uses one style across the codebase.

Option A: Google-style sections

defcalculate_total(prices):
"""
    Calculate the total of a list of prices.

    Args:
        prices: List of numbers (int or float).

    Returns:
        The sum of all prices.
    """
returnsum(prices)

Option B: NumPy-style sections

defcalculate_total(prices):
"""
    Calculate the total of a list of prices.

    Parameters
    ----------
    prices : list[float]
        List of prices.

    Returns
    -------
    float
        Total price.
    """
returnsum(prices)

Pick one style and apply it consistently in new code.


6) Write docstrings that help real users of the code

Good docstrings answer practical questions:

  • What does this do, in one sentence?
  • What inputs are expected, and what happens with bad input?
  • What does it return, and what types should callers expect?
  • Are there edge cases or limits worth calling out?
defparse_age(text):
"""
    Parse an age from user input.

    Accepts strings like "34" or " 34 ".
    Raises ValueError if the input is not a whole number.
    Returns the age as an int.
    """
returnint(text.strip())

Examples you can copy

1) Function docstring with a short example

defslugify(title):
"""
    Convert a title into a URL-friendly slug.

    Example:
        slugify("Hello World") -> "hello-world"
    """
returntitle.strip().lower().replace(" ","-")

2) Module docstring that explains file responsibilities

"""
API client for the billing service.

Expose a small set of functions that wrap HTTP calls.
Keep request details here so the rest of the app stays clean.
"""

3) Class and method docstrings that avoid repetition

classEmailSender:
"""
    Sends transactional emails.

    This class wraps a provider client and exposes simple methods
    for common email types.
    """

defsend_welcome(self,to_address):
"""
        Send a welcome email to a single address.
        """
        ...

Common mistakes and how to fix them

Mistake 1: Putting the docstring in the wrong place

You might write:

defgreet(name):
print("Hello",name)
"""
    Print a friendly greeting.
    """

Why it breaks:

A docstring only counts when it is the first statement inside the function, class, or module.

Correct approach:

defgreet(name):
"""
    Print a friendly greeting.
    """
print("Hello",name)

Mistake 2: Using docstrings for inline notes

You might write:

total=0
"""
Update total for each price.
"""
forpriceinprices:
total+=price

Why it breaks:

This creates a string literal that does not document a function, class, or module. It can confuse readers and tools.

Correct approach:

total=0
# Update total for each price.
forpriceinprices:
total+=price

Mistake 3: Writing docstrings that repeat the code

You might write:

defadd(a,b):
"""
    Add a and b.
    """
returna+b

Why it breaks:

It does not add useful information for callers.

Correct approach:

defadd(a,b):
"""
    Add two numbers and return the result.

    Use this when you want a single place to validate numeric inputs.
    """
returna+b

Troubleshooting

If your docstring does not show up in help(your_function), confirm it is the first statement right under def or class.

If a docstring is ignored at the top of a file, move it above imports and other code.

If your docstrings look inconsistent across files, pick one style and update new code first.

If docstrings become too long, move deep details into external documentation and keep a short summary plus key rules in code.


Quick recap

  • Use triple quotes for multi-line documentation with docstrings.
  • Put module docstrings at the top of the file, before imports.
  • Put function, class, and method docstrings as the first statement inside them.
  • Pick a docstring style such as Google or NumPy and stay consistent.
  • Write docstrings that explain behavior, inputs, outputs, and edge cases.