Search⌘ K

NamedTuple Classes

Understand how to use typing.NamedTuple for immutable data structures and explore the design choice between inheritance and composition. Learn to build composite classes in Python for clean and maintainable code.

Overview

Using typing.NamedTuple is somewhat similar to using @dataclass(frozen = True). There are some significant differences in the implementation details, however. In particular, the typing.NamedTuple class does not support inheritance in the most obvious way. This leads us to a design based on composition of objects in the Sample class hierarchy. With inheritance, we’re often extending a base class to add features. With composition, we’re often building multi-part objects of several different classes.

Here’s the definition of Sample as NamedTuple. It looks similar to the @dataclass definition. The definition of KnownSample, however, must change dramatically:

Python 3.10.4
class Sample(NamedTuple):
sepal_length: float
sepal_width: float
petal_length: float
petal_width: float
class KnownSample(NamedTuple):
sample: Sample
species: str

The ...