runtime

compare approaches one problem · two ways

Compare Approaches

The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.

Hand-written class vs @dataclass

A product record that prints nicely and compares by value.

what differs

@dataclass writes __init__, __repr__ and __eq__ from the annotated fields. Options add ordering (order=True), immutability (frozen=True) and smaller instances (slots=True).

at a glance

approachuse it when
A · plain classThe class has real behaviour and custom construction.
B · @dataclassRecords: data first, behaviour second.

Watch out: Type hints aren't checked at runtime: Product(1, 2, "free") works. Validate in __post_init__ if you need to.

the outputs

Each approach runs on the same input.

concepts

dataclasses__repr____eq__

learn it

Dataclasses: records without the boilerplate

related comparisons

NamedTuple vs frozen dataclass · TypedDict vs dataclass

A · plain class
B · @dataclass
Compare Python Approaches · Runtime