Python

How to Write Docstrings in Python – Best Practices & Examples

Pradeep Kumar

4 mins read
Docstrings in Python

Docstrings in Python: When working on Python projects, especially in teams or open-source environments, readable and maintainable code becomes essential. One of the most effective ways to achieve this is by using docstrings (documentation strings).

A docstring is a special kind of string literal in Python that explains the purpose of a function, class, method, or module. Unlike comments (#), docstrings are stored in the object’s __doc__ attribute and can be accessed at runtime with the built-in help() function.

In this blog, we’ll explore:

  • What Python docstrings are
  • PEP 257 guidelines
  • Popular docstring formats (Google, NumPy, reStructuredText)
  • Examples for functions, classes, and modules
  • Best practices to follow

📌 What is a Docstring in Python?

A docstring is written inside triple quotes (""" or ''') and placed immediately after a function, class, or module definition.

Example:

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

print(add.__doc__)
# Output: Return the sum of two numbers.

This makes docstrings more powerful than inline comments because they are:

  • Machine-readable (used by tools like Sphinx, PyDoc, IDEs)
  • Accessible at runtime (help(), .__doc__)
  • Standardized under PEP 257

📖 PEP 257 – Docstring Conventions

PEP 257 defines the standard style for docstrings in Python. Key points include:

  1. Use triple quotes (""") for all docstrings.
  2. First line should be a short summary.
  3. If more details are needed, leave a blank line, then add explanation.
  4. End multiline docstrings with """ on a new line.
  5. Keep line length under 72 characters (for readability).

📂 Types of Docstrings

Docstrings can be written in different formats, depending on your project style or tooling needs.

1. Google Style Docstrings

def multiply(a, b):
    """Multiply two numbers.

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

    Returns:
        int: The product of the two numbers.
    """
    return a * b

2. NumPy Style Docstrings

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

    Parameters
    ----------
    a : float
        Numerator.
    b : float
        Denominator.

    Returns
    -------
    float
        The result of division.
    """
    return a / b

3. reStructuredText (Sphinx)

def subtract(a, b):
    """
    Subtract two numbers.

    :param a: The first number.
    :type a: int
    :param b: The second number.
    :type b: int
    :return: Difference of a and b.
    :rtype: int
    """
    return a - b

📘 Docstrings for Functions and Methods

def greet(name: str) -> str:
    """Return a greeting message.

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

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

📗 Docstrings for Classes

class Car:
    """A class to represent a car.

    Attributes:
        brand (str): The brand of the car.
        model (str): The model of the car.
    """

    def __init__(self, brand, model):
        """Initialize the car with brand and model."""
        self.brand = brand
        self.model = model

    def display_info(self):
        """Display the car information."""
        return f"{self.brand} {self.model}"

📙 Docstrings for Modules

At the top of a Python file, you can write a module docstring:

"""
math_utils.py

This module provides basic mathematical operations:
- add
- subtract
- multiply
- divide
"""

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

✅ Best Practices for Writing Docstrings

  • Always use triple double quotes (""")
  • Keep the first line short and descriptive
  • Use a consistent style (Google, NumPy, or reST)
  • Include argument types and return values
  • Document edge cases and exceptions if needed
  • Follow PEP 8 along with PEP 257 for clean formatting
  • Update docstrings when code changes

🔎 Tools to Generate and Check Docstrings

  • PyDoc → Generates HTML documentation
  • Sphinx → Advanced documentation generator
  • Doxygen → Cross-language documentation
  • pydocstyle → Linter for checking PEP 257 compliance

🎯 Conclusion

Writing docstrings in Python is more than just adding comments. It’s about making your code self-explanatory, maintainable, and professional. By following PEP 257 guidelines and choosing a consistent docstring style (Google, NumPy, or reST), you ensure that your project remains easy to understand—for both humans and machines.

Pradeep Kumar

Passionate about technology and sharing insights on web development and digital transformation.

Found this helpful? Share it!

Recommended Reading

View all