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.
We'll cover the following...
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:
The ...