2.2 Immutable data
Since we’re not using variables to track the state of a computation, our focus needs to stay on immutable objects. We can make extensive use of tuples, typing.NamedTuples
, and frozen @dataclass
to provide more complex data structures that are also immutable. We’ll look at these class definitions in detail in Chapter 7, Complex Stateless Objects.
The idea of immutable objects is not foreign to Python. Strings and tuples are two widely-used immutable objects. There can be a performance advantage to using immutable tuples instead of more complex mutable objects. In some cases, the benefits come from rethinking the algorithm to avoid the costs of object mutation.
As an example, here’s a common design pattern that works well with immutable objects: the wrapper()
function. A list of tuples is a fairly common data structure. We will often process this list of tuples in one of the two following ways:
Using higher-order functions: As shown earlier...