Annotations for documentation, tooling, and catching bugs before runtime
Modern Python codebases — especially at FAANG and AI companies — use type hints extensively. They power IDE autocompletion, enable static analysis (mypy, pyright), and make function signatures self-documenting. They catch type errors at development time that would otherwise surface as cryptic runtime bugs.
Modern Python codebases — especially at AI and tech companies — expect annotated code. Type hints signal production hygiene and make Optional, Protocol, and generics part of everyday vocabulary.
Type Hints are annotations — Python itself ignores them at runtime entirely. They exist for humans and for tools. Think of them as a machine-readable docstring that tools can verify. Protocol is Python's structural typing — "any class that has these methods" — making duck typing explicit and tool-checkable.
Annotate function parameters and return types with their expected types. Optional[X] signals a value that may be absent; the | union syntax allows multiple types. Python ignores annotations at runtime — they exist for tools and humans.
Optional[X] is shorthand for X | None — use it whenever a value may be absent. Built-in generics like list[int] and dict[str, float] need no import in Python 3.9+.
TypeVar lets you write generic functions where the input and output types stay consistent. Protocol formalises duck typing — any class with the required methods satisfies it, no inheritance needed.
Protocol is duck typing made tool-checkable. Any class with the required methods satisfies the protocol — no inheritance, no registration. This is how Python's own built-in protocols work: anything with __len__ is a Sized.
Annotations for three advanced patterns: typing functions passed as values, adding type information to plain dicts, and marking constants that should never be reassigned.
Callable[[ArgTypes], ReturnType] types functions passed as values. TypedDict adds type information to a plain dict — lighter than a full class, works anywhere a dict is expected. Final marks a name as a constant; type checkers will flag any reassignment.