Lesson · Dataclasses, Enums & Data Modeling
Named Tuples
55 min readNamed Tuples
Named tuples provide lightweight immutable records with named fields and tuple behavior. They are excellent for simple fixed data and less suitable once validation or rich behavior grows.
Learning goals
- Compare the two definition forms: the
collections.namedtuplefactory call and thetyping.NamedTupleclass statement with annotations. - Read fields by name and by index, and unpack a named tuple like a regular tuple.
- Explain why named tuples are immutable and what that means for hashing and sharing.
- Update a record safely with
_replaceand say what it returns. - Choose between a named tuple and a dataclass for a given record using mutability and behavior needs.
Mental model
Both forms produce the same thing: a subclass of tuple whose fields have names, so point.x and point[0] reach the same value and x, y = point unpacks by position. Immutability is inherited from tuple, which makes instances hashable and safe to share but blocks updates; the moment a record needs mutation, validation, or methods, the last line of the fence points to dataclasses.
Mental model
read it top to bottom
collections.namedtuple("Point", "x y") factory form, builds a class from a field list
class Point(NamedTuple): x: int; y: int class form with annotations
↓ both produce
an immutable tuple subclass with named, positionally indexed fields
↓ reads by name or index, unpacks like any tuple, hashes like a tuple
↓ need mutation, validation, or methods? use a dataclass insteadCore idea
A named tuple is a tuple that gained names: its fields are readable by attribute, still indexable and unpackable by position, and immutable because tuple itself is. Both definition forms produce the same class, collections.namedtuple("Point", "x y") as a factory and class Point(NamedTuple) with annotations, so the choice is style and tooling rather than semantics. What named tuples do not provide is room to grow: when the record needs updates or methods, a dataclass takes over.
collections.namedtuple
collections.namedtuple is a factory: Point = namedtuple("Point", "x y") generates and returns a new class that subclasses tuple with named fields. It predates the class syntax and remains the shortest way to build a record from a field list held in data. The generated class exposes helpers such as _fields and _replace on every instance.
typing.NamedTuple
typing.NamedTuple is the class-statement form: declare x: int and y: int in the class body and the metaclass builds the same tuple subclass, with annotations available to type checkers. class Point(NamedTuple) in the worked example is equivalent at runtime to the factory call. Methods can be added in the body, and defaults written as x: int = 0 are applied to the rightmost fields.
Immutable record-like data
A named tuple is immutable record-like data: the field values are fixed when the instance is built, and there is no supported way to assign point.x = ... afterwards. Immutability makes instances hashable and safe to share, and updates happen by building a replacement, usually with _replace. The trade is that every change allocates a new object and nothing can be edited in place.
NamedTuple vs dataclass
The comparison comes down to what the record must do. A named tuple is a tuple first: indexing, unpacking, and other tuple behaviors come free, but it cannot grow new state and the factory form gets awkward once validation appears. A dataclass gives up tuple behavior for readable field declarations, defaults, validation hooks, and methods. Pick the named tuple for simple fixed data that flows through tuple-shaped code, and the dataclass once behavior or updates appear.
Walkthrough
class Point(NamedTuple)withx: intandy: intbuilds atuplesubclass whose names bind positions 0 and 1;Point(3, 4)is a tuple of two ints that also answers to.xand.y.x, y = pointunpacks by position, exactly like any sequence, which is why the same object serves both attribute-style and tuple-style code.print(point.x, x, y)prints3 3 4:point.xreads through the name, while the unpackedxandycame from the same underlying positions.- Predict before running: the line
3 3 4, and whatpoint.x = 10does (raisesAttributeError).
Experiments to try
- Call
point._replace(x=7)and check the result: a newPoint(7, 4)while the originalpointstill printsPoint(x=3, y=4). - Print
point._fields,point._asdict(), andpoint[0]; state what each returns and how each relates to position 0. - Try
point[0] = 9andpoint.x = 9, read both error messages, and explain why the tuple machinery blocks the first before any field logic runs. - Define
Pointa second time withcollections.namedtuple("Point", "x y")and compare_fields, indexing, and unpacking with the worked example's class.
Common mistakes
- Expecting
_replaceto mutate in place: it returns a new instance, so ignoring the return value means no change happened at all. - Assigning extra attributes to an instance, which raises
AttributeErrorbecause the generated class uses__slots__ = ()and instances have no__dict__. - Treating
isinstance(value, tuple)as "plain tuple": named tuples are tuples, so the check matches both and cannot distinguish a record from raw positional data. - Forcing a named tuple to grow validation or rich behavior instead of switching to a dataclass, which handles defaults, checks, and methods without fighting the tuple API.
Practice: Easy
- Run the worked example and record the printed line; then print
pointandlen(point)and explain why both a record and a tuple describe it. - Print
point[0]andpoint.x, then unpack withx, y = point; state which access forms read the same value. - Attempt
point.x = 10and record the exception; explain which base class is responsible for the block.
Practice: Medium
- Define
Pointa second time withcollections.namedtupleand compare_fields, indexing, and unpacking with thetyping.NamedTupleversion. - Build
Employee = namedtuple("Employee", "name department")and rewrite a function that returned plain tuples to return it instead; list which call sites become clearer. - Create the same
Point(x, y)record as a named tuple and as a dataclass; test equality and ordering on both and note which behaviors came for free in each case.
Practice: Hard
- Design a
Versionnamed tuple subclass with anext_patch()method returningself._replace(patch=self.patch + 1); test that the original version never changes across calls. - Build a failure lab: a
_replacecall whose return value is discarded (the mutation that never happened); an extra attribute assignment and theAttributeErrorfrom__slots__; a defaulted field placed before a non-defaulted one in class syntax and theTypeErrorit raises. Explain each mechanism and the fix. - Connect this lesson to dataclasses: rewrite the
Versiontype as a frozen dataclass and compare what the two versions trade (tuple interoperability versus class syntax and room for methods and validation).
Lesson checklist
- I can define the same record with
collections.namedtupleand withtyping.NamedTupleand say how the two differ. - I can read named fields, index positions, and unpack a named tuple in one line.
- I can update a record safely with
_replaceand explain why the original is unchanged. - I can choose between a named tuple and a dataclass based on mutability and behavior needs.
Remember
A named tuple is a tuple with field names: define it with the `collections.namedtuple` factory or the `typing.NamedTuple` class statement and you get the same immutable, unpackable, hashable record. The worked example's `Point` shows the dual nature, reading `3` through `point.x` and through unpacked positions; when a record needs updates, validation, or methods, the dataclass from the previous lesson is the tool that grows.
Interview angles
What is the main purpose of **collections.namedtuple**?+
collections.namedtuple is a factory that builds a tuple subclass with named fields: Point = namedtuple("Point", "x y") produces the same kind of class the worked example declares with typing.NamedTuple. Fields stay readable by name and by index, and instances are immutable because they are tuples.
What should you pay attention to when using **typing.NamedTuple**?+
typing.NamedTuple is the class-statement form: declare annotations and the metaclass builds the same tuple subclass, adding type information for checkers. class Point(NamedTuple) with x: int and y: int is the worked example, where point.x and x, y = point both read the same values.
How does **Immutable record-like data** fit into this lesson?+
A named tuple stores immutable record-like data: field values are fixed at construction, so the instance is hashable and safe to share. Updates happen by building a replacement with _replace, which is why the original point never changes.
What does `_replace` return, and why does that matter for immutable records?+
_replace builds and returns a new instance with the given fields swapped in; the original stays as it was. Code that calls point._replace(x=7) and discards the return value has performed no mutation, which is the classic trap with immutable records.