Documentation & Type Hints
Writing code that “works” is only 50% of the job. The other 50% is ensuring that other humans (including yourself in 6 months) can understand why and how it works. Python provides two primary tools for this: Docstrings and Type Hints.
1. Professional Docstrings
Section titled “1. Professional Docstrings”A Docstring is a triple-quoted string that appears at the very top of a function, class, or module.
Google Style (Recommended)
Section titled “Google Style (Recommended)”This is widely used in the industry for its readability and clean structure.
def fetch_user(user_id: int, include_metadata: bool = False): """ Retrieves a user from the database.
Args: user_id (int): The unique identifier for the user. include_metadata (bool): If True, returns extended stats.
Returns: dict: The user data mapping.
Raises: UserNotFoundError: If the ID does not exist in the database. """ passNumPy Style
Section titled “NumPy Style”Common in the scientific and data science community. It uses dashes to separate sections.
2. Modern Type Hints (PEP 484)
Section titled “2. Modern Type Hints (PEP 484)”Type hints tell developers (and IDEs) what kind of data a function expects. Python doesn’t enforce these at runtime, but they make your code significantly easier to debug.
from typing import List, Dict, Optional, Union
def process_scores(scores: List[float]) -> Dict[str, Union[float, str]]: avg = sum(scores) / len(scores) return { "average": avg, "status": "PASS" if avg > 50 else "FAIL" }Why use Type Hints?
Section titled “Why use Type Hints?”- Autocomplete: Your IDE (VS Code/PyCharm) can provide better suggestions.
- Static Analysis: Tools like
mypycan find bugs before you even run your code. - Documentation: The types serve as a form of living documentation.
3. Self-Documenting Code
Section titled “3. Self-Documenting Code”The best documentation is code that doesn’t need comments.
- Avoid:
x = 86400 # seconds in a day - Prefer:
SECONDS_IN_DAY = 86400
4. Automatic Documentation Tools
Section titled “4. Automatic Documentation Tools”Professional teams use tools to turn their docstrings into beautiful websites (like this one!).
- Sphinx: The industry standard for large projects.
- MkDocs: A modern, Markdown-based alternative.
- pdoc: The simplest way to generate API docs on the fly.
5. Summary Table
Section titled “5. Summary Table”| Feature | Purpose | Tool |
|---|---|---|
| Docstrings | Explain the intent and usage. | help(func) |
| Type Hints | Define data structures. | mypy |
| Comments | Explain the “Why” (not the “What”). | # |
| Linters | Check for missing docs. | ruff |