Skip to main content
Guide

How to Document Python Code

A complete guide to writing effective Python documentation with docstrings, type hints, and modern tools.

What you'll learn

  • Write effective docstrings using Google, NumPy, and Sphinx formats
  • Add type hints for better documentation and IDE support
  • Generate documentation automatically with tools
  • Best practices for Python API documentation

Why Document Python Code?

Good documentation reduces onboarding time by 50% and decreases support requests. Python's dynamic nature makes documentation even more critical - without type hints and docstrings, developers have to read implementation code to understand interfaces.

Python Docstring Formats

Python supports several docstring formats. Here are the most common:

1. Google Style (Recommended)

def calculate_total(price: float, tax_rate: float = 0.1) -> float:
    """Calculate total price including tax.

    Args:
        price: Base price before tax.
        tax_rate: Tax rate as decimal (default 0.1 for 10%).

    Returns:
        Total price with tax applied.

    Raises:
        ValueError: If price is negative.

    Example:
        >>> calculate_total(100, 0.08)
        108.0
    """
    if price < 0:
        raise ValueError("Price cannot be negative")
    return price * (1 + tax_rate)

2. NumPy Style

def calculate_total(price, tax_rate=0.1):
    """
    Calculate total price including tax.

    Parameters
    ----------
    price : float
        Base price before tax.
    tax_rate : float, optional
        Tax rate as decimal (default is 0.1).

    Returns
    -------
    float
        Total price with tax applied.
    """
    return price * (1 + tax_rate)

3. Sphinx/reStructuredText Style

def calculate_total(price, tax_rate=0.1):
    """Calculate total price including tax.

    :param price: Base price before tax.
    :type price: float
    :param tax_rate: Tax rate as decimal.
    :type tax_rate: float
    :returns: Total price with tax applied.
    :rtype: float
    """
    return price * (1 + tax_rate)

Type Hints for Better Documentation

Python 3.5+ supports type hints which serve as inline documentation and enable IDE autocompletion:

from typing import List, Optional, Dict

class UserService:
    """Service for managing user operations."""

    def get_user(self, user_id: int) -> Optional[Dict[str, str]]:
        """Fetch user by ID."""
        ...

    def list_users(self, limit: int = 100) -> List[Dict[str, str]]:
        """List all users with optional limit."""
        ...

Documentation Generation Tools

Sphinx

The standard Python documentation generator. Powerful but requires configuration.

pip install sphinx

MkDocs

Fast, simple documentation with Material theme. Good for smaller projects.

pip install mkdocs

pdoc

Auto-generates API docs from docstrings. Zero configuration.

pip install pdoc

AutomaDocs

AI-powered docs that generate automatically and stay in sync with your code.

Try free →

Best Practices

  1. Document public APIs first - Focus on functions and classes others will use
  2. Include examples - Show how to use the code, not just what it does
  3. Keep it updated - Outdated docs are worse than no docs
  4. Use type hints - They document types and enable IDE features
  5. Document exceptions - List what errors can be raised

Automate Documentation Updates

The hardest part of documentation is keeping it current. Tools like AutomaDocs can:

  • Generate documentation from code automatically
  • Update docs when code changes via GitHub webhooks
  • Provide AI chat to answer questions about your codebase

Try AutomaDocs Free

Connect your Python repository and get comprehensive documentation in 60 seconds. No configuration required.