Python Docstrings The Complete Guide (Types, Examples, Best Practices & PEP 257)
Python Docstrings
Python Tutorial > Python Docstrings > Python Docstrings: The Complete Guide (Types, Examples, Best Practices & PEP 257)
Posted in

Python Docstrings: The Complete Guide (Types, Examples, Best Practices & PEP 257)

Learn everything about Python docstrings in this complete guide. Understand what docstrings are, how to write and access them, the different formats (Google, NumPy, Sphinx), best practices, PEP 257 conventions, and docstring vs comments with examples. Perfect for beginners and advanced developers.

Introduction

What Are Docstrings?

The Syntax:

Example of a Docstring

def greet(name):
    """Return a greeting message for the given user."""
    return f"Hello, {name}!"

Key Characteristics

How to Create and Access Docstrings

Creating Docstrings

Rules for Valid Docstrings

Examples of Docstrings

def add(a, b):
    """Add two numbers and return the result."""
    return a + b
class Person:
    """A class representing a person with name and age."""
    
    def __init__(self, name, age):
        """Initialize person object."""
        self.name = name
        self.age = age
"""
This module provides utility functions for string processing.
Includes uppercase conversion and trimming functions.
"""
class Calculator:
    """A basic calculator class."""

    def subtract(self, x, y):
        """Return the result of subtracting y from x."""
        return x - y

Accessing Docstrings

def greet(name):
    """Return a greeting message for the given name."""
    return f"Hello, {name}!"
def greet(name):
    """Return a greeting message for the given name."""
    return f"Hello, {name}!"

help(greet)
Help on function greet in module __main__:

greet(name)
    Return a greeting message for the given name.

B) Accessing Docstrings Using the __doc__ Attribute

def square(n):
    """Return the square of a number n."""
    return n * n
def square(n):
    """Return the square of a number n."""
    return n * n

print(square.__doc__)
Return the square of a number n.

Important Differences Between help() and __doc__

Featurehelp()__doc__
ReturnsFormatted, readable outputRaw docstring string
Good forInteractive inspectionCode automation and introspection
Adds metadataYes (signature, module info)No
Uses __doc__ internallyYesN/A
def divide(a, b):
    """
    Divide a by b and return the result.

    Raises:
        ZeroDivisionError: If b is zero.
    """
    return a / b

print(divide.__doc__)   # Raw docstring
help(divide)            # Formatted docstring

Where to Place Docstrings (Docstring Must Be the First Statement)

def greet():
    """This function prints a greeting."""
    print("Hello!")     # Output: This function prints a greeting.
def greet():
    print("Hello!")
    """This will NOT be recognized as a docstring."""

print(greet.__doc__)    # Output: None

Docstring Structures vs. Docstring Styles

Docstring Structure Types

A) Single-Line Docstring

def is_even(n):
    """Return True if n is an even number."""
    return n % 2 == 0

B) Multi-Line Docstring

def calculate_area(radius):
    """
    Calculate the area of a circle.

    Parameters:
        radius (float): Radius of the circle.

    Returns:
        float: The computed area.
    """
    return 3.14159 * radius * radius

Docstring Style Types

A) Google Style Docstrings

def greet(name):
    """
    Generate a greeting message.

    Args:
        name (str): The name of the person.

    Returns:
        str: A formatted greeting message.
    """
    return f"Hello, {name}!"

B) NumPy / SciPy (NumPyDoc) Style Docstrings

def normalize(x):
    """
    Normalize a list of numbers.

    Parameters
    ----------
    x : list of float
        Input values.

    Returns
    -------
    list of float
        Normalized values.
    """
    total = sum(x)
    return [i / total for i in x]

C) reStructuredText (reST) / Sphinx Style Docstrings

def divide(a, b):
    """
    Divide two numbers.

    :param a: Numerator.
    :type a: float
    :param b: Denominator.
    :type b: float
    :returns: The result of the division.
    :rtype: float
    :raises ZeroDivisionError: If b is zero.
    """
    return a / b

Docstring vs Comments in Python

FeatureCommentsDocstrings
PurposeExplain code logic for developersDocument functions/classes/modules
Syntax# for single-line comments""" triple-quoted string """
PlacementAnywhere in codeImmediately after function/class/module header
ExecutionIgnored by interpreterStored as part of the object
Runtime AccessNot accessibleAccessible via __doc__ or help()
Documentation ToolsNot includedIncluded in Sphinx, pydoc, help()
Best ForExplaining why / complex logicExplaining what / API documentation
VisibilityOnly for developers reading codeVisible to users calling help()
PEP GuidancePEP 8 covers commentsPEP 257 covers docstrings

Example Showing the Difference

def greet(name):
    """Return a personalized greeting message."""  # Docstring stored

    # This is an inline comment for developers
    return f"Hello, {name}!"
Return a personalized greeting message.

PEP 257 Recommendations for Docstrings

def greet():
    """Return a simple greeting."""
    return "Hello!"
def add(a, b):
    """Add two numbers and return the result."""
    return a + b
def factorial(n):
    """
    Compute the factorial of a number.

    This function uses a recursive approach to compute the factorial.
    """
def divide(a, b):
    """
    Divide one number by another.

    Parameters:
        a (float): Numerator.
        b (float): Denominator (must not be zero).

    Returns:
        float: Result of division.

    Raises:
        ZeroDivisionError: If b is zero.
    """
def square(n):
    """Return the square of a number."""
class Person:
    """Represent a person with a name and age."""
def process():
    """
    Perform a processing task.

    This function does something important.
    """

Summary of Key PEP 257 Rules

Common Mistakes to Avoid When Writing Docstrings

def process(data):
    """
    Loop through the list, check each item, and append matches to result.
    """
def process(data):
    """
    Filter the input list and return only items that match the criteria.
    """
def example():
    """Do something.
    More explanation…
    """
def example():
    """
    Do something.

    More explanation…
    """
"""Return x + 1."""   # The code already tells this.
"""Return the incremented value of x by applying business logic."""
def add(a, b):
    # comment here
    """Add two numbers."""
def add(a, b):
    """Add two numbers."""

Conclusion

Next Post
Python Docstrings: The Ultimate FAQ Guide (With Examples & Best Practices)

Suggested Posts
1. Python Docstrings: The Ultimate FAQ Guide (With Examples & Best Practices)

4 thoughts on “Python Docstrings: The Complete Guide (Types, Examples, Best Practices & PEP 257)

Leave a Reply

Your email address will not be published. Required fields are marked *