Type Hints
py-type-hints
Code Snippets
dataclass Basics
`@dataclass` writes the boring boilerplate for you: `__init__`, `__repr__`, and `__eq__`. You declare fields with type hints and (optionally) defaults, and Python builds the constructor and the value-equality semantics. This entry covers the basic shape, default values done right, and the `field()` escape hatch for mutable defaults.
Optional, Union, Literal Type Hints
Modern Python type hints (3.10+) replaced most of `typing.Optional` and `typing.Union` with the `X | Y` operator and made `Literal` the right tool for closed string sets. This entry covers `T | None` for nullable values, `X | Y` for unions, and `Literal['a', 'b']` for enum-like APIs, with runtime examples that show why each shape matters.
Frozen + slots Dataclasses
`@dataclass(frozen=True)` makes instances immutable and hashable, which lets you use them as dict keys or set members. `slots=True` (3.10+) skips the `__dict__` allocation, saving roughly 40% of memory per instance and making attribute access slightly faster. This entry covers each flag separately and shows when combining them is the right call.
Structural Typing with Protocol
`typing.Protocol` adds static structural typing (duck typing) to Python: any object that has the right methods is acceptable, no inheritance required. It is the right tool for plugin interfaces, dependency injection, and 'looks like a file' style APIs. This entry covers a basic protocol, the `@runtime_checkable` switch, and how Protocol differs from an abstract base class.
Community
Type Hints, mypy, and the Runtime Truth
Python type hints are documentation that a static checker reads. The runtime ignores them. Here is what hints do, what mypy adds, and the libraries that validate at runtime on purpose.
dataclasses, attrs, and pydantic: Pick One
Three libraries solve the data-container problem and they answer different questions. dataclasses for internal objects, attrs for power-user customisation, pydantic for validating external input.
