EMZETT.
Login

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) shows Product(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=True makes objects immutable and hashable, order=True generates ordering comparisons, slots=True saves memory.
  • __post_init__: Runs after the constructor, for checks or derived fields.
  • Helpers: asdict(p) and replace(p, price=5) (copy with a change).
  • Comparison: NamedTuple is immutable and tuple-like, dict has no fixed structure, Pydantic additionally validates at runtime.

See also: type hints