Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Standard library & toolingMiddleOccasionalTheory

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

Python example
Point = namedtuple("Point", ["x", "y"])

still supports

Python example
x, y = point

unpacking and

Python example
point[0]

, which a `@dataclass` version would not support without adding `__iter__` and `__getitem__` manually.

#collections#namedtuple#dataclasses

Sources

collections — Container datatypesPython Software Foundation · deque, defaultdict, Counter, namedtuple and ChainMap semanticsdataclasses — Data ClassesPython Software Foundation · Generated dunder methods, field defaults and frozen/eq/order semantics