Python Patterns
Iron Law
EXPLICIT IS BETTER THAN IMPLICIT [3]
Type-hint every function signature. Name every exception. Use dataclasses over raw
dicts. Python's flexibility is a strength only when boundaries are explicit.
Type Safety
- Annotate every parameter and the return:
def process(data: list[dict[str, Any]], config: AppConfig) -> ProcessResult, notdef process(data, config). - Use
from __future__ import annotationsfor forward references, not string annotations (x: "MyClass"). - Use
Protocolfor structural typing, over ABC: any class with matching methods satisfies it, with noimplements. - Write optionals as
User | None(PEP 604), notOptional[User], and handleNoneexplicitly.
Error Handling
- Define custom exception types: a base
AppError(Exception)and subclasses (NotFoundError) that carry structured fields (entity,id). - Catch named exceptions,
except (ValueError, KeyError):. Never a bareexcept:: it catchesSystemExit. - Use context managers for resource cleanup and the unit of work: commit on success, roll back and re-raise on error.
Data Modeling
- Use
@dataclass(frozen=True)for internal value objects, withfield(default_factory=...)for computed defaults. - Use Pydantic models at API boundaries: they validate on instantiation (
EmailStr,Field(ge=0, le=150)). - Use
@dataclassfor domain objects and Pydantic for API models — not interchangeably, and not raw dicts.
Pythonic Patterns
- Comprehensions over loops:
[u.name for u in users if u.active]. enumerate(items), notrange(len(items)).- EAFP over LBYL:
try: value = mapping[key]withexcept KeyError. - No mutable default arguments:
def fn(items: list | None = None), notdef fn(items=[]). - Compose smaller focused classes, not a 50-method god class.
- Tests use pytest fixtures, no repeated setup.
Extended References
references/sources.md— Full bibliographyreferences/patterns.md— Extended patterns: DI, decorators, fixturesreferences/violations.md— Violation examples with citationsreferences/detection.md— Grep patterns for Python issuesreferences/async.md— Async patterns: gather, TaskGroup, generators