7.8 Summary
In this chapter, we looked at different ways to use NamedTuple
subclasses to implement more complex data structures. The essential features of a NamedTuple
are a good fit with functional design. They can be created with a creation function and accessed by position as well as name.
Similarly, we looked at frozen dataclasses as an alternative to NamedTuple
objects. The use of a dataclass seems slightly superior to a NamedTuple
subclass because a dataclass doesn’t also behave like a sequence of attribute values.
We looked at how immutable objects can be used instead of stateful object definitions. The core technique for replacing state changes is to wrap objects in larger objects that contain derived values.
We also looked at ways to handle multiple data types in Python. For most arithmetic operations, Python’s internal method dispatch locates proper implementations. To work with collections, however, we might want to handle iterators and sequences slightly differently...