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.

NamedTuple vs frozen dataclassbehaves differently

An immutable point you can unpack, compare and update.

what differs

A NamedTuple is a tuple: it unpacks, indexes, and equals a plain tuple with the same values. A frozen dataclass is its own type: it only equals another Point.

at a glance

approachuse it when
A · NamedTupleTuple-like records: unpacking, indexing, compatibility with code that expects tuples.
B · frozen dataclassRecords that shouldn't pretend to be tuples; easier to add methods, defaults and validation.

Watch out: Tuple equality can surprise: Point(1, 2) == Size(1, 2) for two different namedtuple types.

the outputs

Each approach runs on the same input.

concepts

typing.NamedTuplefrozen dataclass

learn it

Dataclasses: records without the boilerplate

related comparisons

Hand-written class vs @dataclass · list vs tuple

A · NamedTuple
B · frozen dataclass
Compare Python Approaches · Runtime