💡 Advanced Python Concepts
Estimated reading: 3 minutes 392 views

Python Docstring Guide – Google, NumPy, RST Formats Explained

Introduction – Why Are Docstrings Important?

Python is celebrated for its readability, and docstrings are central to that. A docstring is a special string that documents:

  • What a module, function, class, or method does
  • What parameters it takes and returns
  • Why it exists and how to use it

Good docstrings improve code maintainability, enable automatic documentation tools like Sphinx, and make interactive help more useful.

In this guide, you’ll learn:

  • How to write effective docstrings for modules, functions, classes
  • Different docstring styles (Google, NumPy, reStructuredText)
  • Real-world formatting examples
  • Best practices and linting tools

What Is a Python Docstring?

A docstring is a string literal that appears as the first statement in a module, class, or function.

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

Accessible via help() or .__doc__.


Docstring Types & Placement

Module Docstring

"""math_utils.py - Utility functions for mathematical operations."""

Place this at the top of your .py file.


Function Docstring

def add(a, b):
    """Add two numbers and return the result."""
    return a + b

Class and Method Docstring

class Car:
    """A simple car class."""

    def drive(self):
        """Simulate driving the car."""
        pass

Docstring Formatting Styles

Google Style

def multiply(a: int, b: int) -> int:
    """
    Multiply two integers.

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

    Returns:
        int: The product of a and b.
    """
    return a * b

NumPy Style

def divide(a, b):
    """
    Divide one number by another.

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

    Returns
    -------
    float
        Result of the division.
    """
    return a / b

reStructuredText (RST) Style

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

    :param a: First number.
    :type a: int
    :param b: Second number.
    :type b: int
    :return: The difference.
    :rtype: int
    """
    return a - b

Real-World Example – Document a CLI Tool

def parse_args():
    """
    Parse command-line arguments.

    Returns:
        argparse.Namespace: Parsed arguments.
    """
    ...

Docstrings make CLI tools self-documenting and IDE-friendly.


Best Practices for Writing Docstrings

Do This Avoid This
Use triple double-quotes (""")Mixing quote styles
Start with a summary lineJumping into details without overview
Write in present tenseUsing past/future tense
Keep lines ≤ 72 charactersWriting unreadable blocks
Follow a consistent style guideMixing styles within a project

Accessing Docstrings

From Code

print(add.__doc__)

Using help()

help(add)

Works in Python REPL, IDEs, and Jupyter Notebooks.


Tools to Enforce Docstring Quality

ToolPurpose
pydocstyleChecks PEP 257 compliance
flake8-docstringsLints inline with code rules
SphinxGenerates full HTML docs

Summary – Recap & Next Steps

Python docstrings are a foundational part of writing clean, maintainable, and discoverable code. They’re not just for documentation—they’re tools for collaboration, introspection, and automation.

Key Takeaways:

  • Docstrings document functions, classes, methods, and modules
  • Use consistent formats like Google, NumPy, or reStructuredText
  • Include parameters, returns, and brief descriptions
  • Use help() and IDEs to view docstrings dynamically

Real-World Relevance:
Essential for open-source packages, APIs, internal tools, and production-grade systems.


FAQ – Python Docstrings

What’s the difference between a comment and a docstring?

Comments (#) are for developers only.
Docstrings ("""text""") are accessible at runtime via help() or introspection.

Can a function work without a docstring?

Yes, but it’s harder to understand, maintain, or generate documentation from it.

Are docstrings part of the Python standard?

Yes, standardized in PEP 257.

How do I enforce docstring style?

Use tools like pydocstyle, flake8-docstrings, or docformatter.

What’s the best docstring style?

Use Google or NumPy style for consistency and readability.


Share Now :
Share

Python Docstrings

Or Copy Link

CONTENTS
Scroll to Top