Define behavioral interfaces with Protocol, type untrusted boundaries with TypedDict and Pydantic, keep generics through containers, and enforce it all in CI.
- Python 3.12 or newer
- Familiarity with functions and basic annotations
- A project where you can add one type-checked module
In the AI-coding era, type hints are not cosmetic annotations. They serve as machine-readable boundary contracts that constrain LLM code generation and catch regressions before execution.
Structural subtyping with Protocol
Avoid rigid inheritance hierarchies for test doubles and service adapters. Use typing.Protocol to define lightweight behavioral interfaces:
from typing import Protocol
class DataRepository(Protocol):
def get_by_id(self, item_id: str) -> dict | None: ...
def save(self, item_id: str, data: dict) -> None: ...
A mock class or real database driver satisfies DataRepository without subclassing, making unit tests fast and decoupling domain logic from storage implementations.
Strong boundary contracts with TypedDict and Pydantic
When dealing with untrusted JSON from external APIs, use typing.TypedDict for internal shapes and Pydantic models for boundary deserialization and validation.
from typing import TypedDict
class UserProfile(TypedDict):
user_id: int
username: str
is_active: bool
Generic types for reusable containers
Use typing.TypeVar or modern PEP 695 generics (class Container[T]: ... in Python 3.12+) to retain type safety through caches, queues, and API wrappers rather than falling back to Any.
Static verification in development and CI
Type annotations provide value only when enforced. Run static type checkers like Mypy or Pyright in your CI pipeline, and configure pre-commit hooks to block untyped public APIs.
Sources
Refer to the official Python typing documentation for the authoritative reference on Python’s type system specifications.
Verification record
Editorial review of the typing patterns against the Python typing, Pydantic, and Mypy documentation. Verified 2026-09-02.
About the author
Organizational byline for FlyPython guides, verification records, and corrections. Editorial standards and contact details →