Python: dataclasses
In short: A @dataclass automatically generates __init__, __repr__ and comparisons for a class that mainly holds data. This saves a lot of boilerplate.
In more detail: Instead of writing constructor and text representation by hand, you just list the fields with types.
In Depth
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
tags: list[str] = field(default_factory=list)- Automatic:
Product("Mug", 4.5)works,print(p)showsProduct(name='Mug', price=4.5, tags=[]),==compares field by field. - Defaults: Never set mutable defaults (lists, dicts) directly, use
field(default_factory=list). - Options:
frozen=Truemakes objects immutable and hashable,order=Truegenerates ordering comparisons,slots=Truesaves memory. __post_init__: Runs after the constructor, for checks or derived fields.- Helpers:
asdict(p)andreplace(p, price=5)(copy with a change). - Comparison:
NamedTupleis immutable and tuple-like,dicthas no fixed structure, Pydantic additionally validates at runtime.
See also: type hints