7.5 Using pyrsistent to collect data
In addition to Python’s NamedTuple
and @dataclass
definitions, we can also use the pyrsistent
module to create more complex object instances. The huge advantage offered by the pyrsistent
module is that the collections are immutable. Instead of updating in place, a change to a collection works through a general-purpose ”evolution” object that creates a new immutable object with the changed value. In effect, what appears to be a state-changing method is actually an operator creating a new object.
The following example shows how to import the pyrsistent
module and create a mapping structure with names and values:
>>> import pyrsistent
>>> v = pyrsistent.pmap({"hello": 42, "world": 3.14159})
>>> v # doctest: +SKIP
pmap({’hello’: 42, ’world’: 3.14159})
>>> v[’hello’]
42
>>> v[’world...