NamedTuple is immutable, dataclass is mutable by default.
1from typing import NamedTuple2from dataclasses import dataclass34# NamedTuple — immutable5class Point(NamedTuple):6 x: float7 y: float89p = Point(1.0, 2.0)10print(p.x, p.y) # 1.0 2.011# p.x = 3.0 # AttributeError!1213# Dataclass — mutable14@dataclass15class PointDC:16 x: float17 y: float1819p = PointDC(1.0, 2.0)20p.x = 3.0 # OK2122# Frozen dataclass — immutable23@dataclass(frozen=True)24class FrozenPoint:25 x: float26 y: float2728# Comparison29Point(1, 2) == Point(1, 2) # True (tuple comparison)30PointDC(1, 2) == PointDC(1, 2) # True (field comparison)3132# Hashable33hash(Point(1, 2)) # OK — immutable34# hash(PointDC(1, 2)) # TypeError — unhashable
When to use:
NamedTuple: immutable records, dict keys, sets.dataclass: mutable objects, complex logic.frozen dataclass: immutable with methods.