This directory contains comprehensive examples and tutorials for writing excellent Python documentation. Learn how to create clear, helpful, and professional documentation for your Python projects.
- Docstring conventions (Google, NumPy, Sphinx styles)
- Code commenting best practices
- API documentation techniques
- Sphinx documentation setup and usage
- Type annotations integration
- README and project documentation
- Documentation automation and testing
- Common mistakes and how to avoid them
- Beginners: New to Python documentation
- Intermediate: Want to improve documentation quality
- Advanced: Looking for professional documentation techniques
- Teams: Establishing documentation standards
Start here! A comprehensive, step-by-step guide covering all aspects of Python documentation from beginner to expert level.
| File | Topic | Level | Description |
|---|---|---|---|
| 01-docstring-conventions.py | Docstrings | Beginner-Advanced | Complete guide to docstring styles and conventions |
| 02-sphinx-documentation.py | Sphinx | Intermediate-Advanced | Setting up and using Sphinx for documentation |
| 03-api-documentation.py | API Docs | Intermediate-Advanced | Creating comprehensive API documentation |
| 04-code-comments.py | Comments | Beginner-Intermediate | Best practices for code comments |
| 05-readme-files.py | README | Beginner-Intermediate | Writing effective README files |
| 06-type-annotations-docs.py | Type Hints | Intermediate | Integrating type hints with documentation |
| 07-examples-and-tutorials.py | Examples | All Levels | Writing effective examples and tutorials |
| 08-changelog-versioning.py | Versioning | Intermediate | Changelog and version documentation |
# Read the comprehensive tutorial
open python-practices/best-practices/documentation/tutorial/README.md# Run any example file to see documentation in action
python 01-docstring-conventions.py
python 03-api-documentation.py# Use the patterns from the examples in your own code
from typing import List, Optional
def process_data(data: List[str], validate: bool = True) -> Optional[List[str]]:
"""Process a list of data with optional validation.
Args:
data: List of strings to process
validate: Whether to validate data before processing
Returns:
Processed data list, or None if validation fails
Example:
>>> process_data(["hello", "world"])
['HELLO', 'WORLD']
"""
if validate and not data:
return None
return [item.upper() for item in data]Use this checklist to ensure your documentation meets professional standards:
- All public functions have docstrings
- Docstrings include Args, Returns, and Raises sections
- Examples are provided for complex functions
- Type hints are used consistently
- Comments explain WHY, not WHAT
- All public classes and methods documented
- Error conditions clearly explained
- Usage examples provided
- Cross-references between related functions
- README explains purpose and usage
- Installation instructions are clear
- Contributing guidelines exist
- Changelog is maintained
- License is specified
- Examples are tested (doctest)
- Documentation builds without errors
- Links are not broken
- Spelling and grammar checked
# Documentation generation
pip install sphinx sphinx_rtd_theme
# Documentation quality
pip install pydocstyle doc8
# Type checking
pip install mypy
# Testing documentation examples
python -m doctest your_module.py# Initialize Sphinx documentation
mkdir docs
cd docs
sphinx-quickstart
# Build documentation
make html# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: docstring-check
name: Check docstrings
entry: python -m pydocstyle
language: system
files: \.py$| Style | Best For | Pros | Cons |
|---|---|---|---|
| Most projects | Clean, readable | Less structured | |
| NumPy | Scientific code | Very structured | More verbose |
| Sphinx | Complex projects | Rich markup | Steeper learning curve |
def calculate_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle.
Args:
length: Length of the rectangle
width: Width of the rectangle
Returns:
Area of the rectangle
Example:
>>> calculate_area(5.0, 3.0)
15.0
"""
return length * widthclass DataProcessor:
"""Process and analyze data with various methods.
This class provides a unified interface for data processing
operations with built-in validation and error handling.
Attributes:
data: The dataset being processed
config: Configuration options
Example:
>>> processor = DataProcessor(data=[1, 2, 3])
>>> result = processor.normalize()
>>> len(result) == 3
True
"""def advanced_search(
query: str,
filters: Optional[Dict[str, Any]] = None,
sort_by: str = "relevance",
limit: int = 10
) -> List[Dict[str, Any]]:
"""Perform advanced search with filtering and sorting.
Args:
query: Search query string
filters: Optional filters to apply:
- 'category': Filter by category
- 'date_range': Tuple of (start_date, end_date)
- 'tags': List of required tags
sort_by: Sort criteria ('relevance', 'date', 'popularity')
limit: Maximum number of results to return
Returns:
List of search results, each containing:
- 'id': Unique identifier
- 'title': Result title
- 'score': Relevance score
- 'metadata': Additional information
Raises:
ValueError: If query is empty or invalid
TypeError: If filters format is incorrect
Example:
>>> results = advanced_search(
... "python tutorial",
... filters={'category': 'programming'},
... sort_by='popularity',
... limit=5
... )
>>> len(results) <= 5
True
"""class APIError(Exception):
"""Base exception for API-related errors.
Attributes:
message: Human-readable error description
error_code: Machine-readable error identifier
status_code: HTTP status code equivalent
Example:
>>> try:
... raise APIError("Not found", "NOT_FOUND", 404)
... except APIError as e:
... print(f"{e.error_code}: {e.message}")
NOT_FOUND: Not found
"""- Python Documentation Guide
- Sphinx Documentation
- Google Python Style Guide
- NumPy Documentation Style
- Write the Docs Community
- Start with docstrings - They're the foundation of good documentation
- Use examples liberally - They're worth a thousand words
- Test your examples - Use doctest to ensure they work
- Keep it current - Outdated docs are worse than no docs
- Write for your audience - Consider who will read your documentation
- Automate when possible - Use tools to maintain quality
- Get feedback - Ask users what they need
Found an issue or want to improve the documentation examples?
- Report Issues: Open an issue describing the problem
- Suggest Improvements: Propose better examples or explanations
- Submit Pull Requests: Add new examples or fix existing ones
- Share Feedback: Let us know what's helpful or confusing
This documentation and examples are part of the Python Best Practices project and are available under the MIT License.
Remember: Great documentation is a gift to your future self and to everyone who will use your code. Invest the time to do it right! 🎉