How does `collections.namedtuple` compare to a `@dataclass` for representing a small, fixed record?
Answer
`namedtuple` produces a tuple subclass with named fields, so instances remain immutable and behave like a regular tuple in every way that matters — unpackable, indexable by position — while also allowing attribute access by name. Like any tuple, though, a `namedtuple` instance is hashable only if every field it holds is itself hashable; a namedtuple field holding a `list`, for example, makes that instance unhashable too, so hashability is not an unconditional feature of the type. A `@dataclass` produces a regular class, is mutable by default (or immutable if you pass `frozen=True`), supports methods, inheritance, and non-tuple internal storage, and integrates more naturally with type checkers and IDEs. Choose `namedtuple` for a lightweight, tuple-compatible value that must behave exactly like a tuple in existing code; choose `dataclass` for anything that needs mutability, custom methods, or richer typing support.
Strong answer includes
- namedtuple is a real tuple subclass, immutable and positionally unpackable
- namedtuple hashability, like any tuple's, depends on every field being hashable
- dataclass is a regular class, mutable by default, supports methods and inheritance
Practical example
Point = namedtuple("Point", ["x", "y"])still supports
x, y = pointunpacking and
point[0], which a `@dataclass` version would not support without adding `__iter__` and `__getitem__` manually.