Skip to content

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.


A Docstring is a triple-quoted string that appears at the very top of a function, class, or module.

This is widely used in the industry for its readability and clean structure.

google_style.py
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.
"""
pass

Common in the scientific and data science community. It uses dashes to separate sections.


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.

typing_demo.py
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"
}
  1. Autocomplete: Your IDE (VS Code/PyCharm) can provide better suggestions.
  2. Static Analysis: Tools like mypy can find bugs before you even run your code.
  3. Documentation: The types serve as a form of living documentation.

The best documentation is code that doesn’t need comments.

  • Avoid: x = 86400 # seconds in a day
  • Prefer: SECONDS_IN_DAY = 86400

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.

FeaturePurposeTool
DocstringsExplain the intent and usage.help(func)
Type HintsDefine data structures.mypy
CommentsExplain the “Why” (not the “What”).#
LintersCheck for missing docs.ruff