Course contentsShow
← Python
Lesson 195 of 1,0603. Functions and ModularizationFree lesson

Implementing PEP 257 Compliant Docstrings

Learners will master writing structured, descriptive docstrings that adhere to PEP 257 standards to improve code readability and automated documentation generation.

In this lesson, you will learn how to write professional, PEP 257-compliant docstrings that make your code easy to read and ready for automated documentation tools.

What is a Docstring?

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Unlike comments, which are for people reading your code, docstrings are accessible at runtime via the __doc__ attribute and are picked up by tools to generate documentation automatically.

PEP 257 Guidelines

PEP 257 provides the industry-standard conventions for writing these strings. To follow them, use triple double quotes (""") even if the docstring fits on one line.

1. One-line docstrings: For simple functions, keep it brief. End with a period, and close the quotes on the same line.

def add(a, b):
    """Return the sum of two numbers."""
    return a + b

2. Multi-line docstrings: For more complex logic, follow this structure:

  • A one-line summary.
  • A blank line.
  • A more detailed description of the function's behavior.
  • (Optional) Sections detailing arguments and return values.
  • The closing quotes should be on a line by themselves.
def calculate_area(radius):
    """Calculate the area of a circle.

    Takes a radius (int or float) and returns the area based on the
    constant PI. Ensures the radius is non-negative before calculation.
    """
    if radius < 0:
        return 0
    return 3.14 * (radius ** 2)

Why it Matters

When you use a library or collaborate on a project, typing help(function_name) in an interactive console will display your docstring. By adhering to PEP 257, you ensure that your code feels native to the Python ecosystem. Your summaries should be imperative (e.g., "Return the sum" rather than "Returns the sum"), describing what the function does rather than how it works internally.

Key Takeaway: Use triple double quotes for all docstrings, provide a concise imperative summary as the first line, and separate detailed explanations from the summary with a blank line.