Dataclasses
py-dataclasses
Code Snippets
namedtuple for Lightweight Records
`collections.namedtuple` produces a tuple subclass with named fields, giving you the immutability and packing of a tuple plus the readability of a dataclass. It is the right choice for tiny return-record types that should be cheap and hashable. This snippet covers the basic factory, the typed `NamedTuple` form from `typing`, and the `_replace` and `_asdict` helpers for record-style updates and JSON conversion.
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.
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.
