Using typing.NamedTuple for immutable objects
In some cases, an object is a container of rather complex data, but doesn't really do very much processing on that data. Indeed, in many cases, we'll define a class that doesn't require any unique method functions. These classes are relatively passive containers of data items, without a lot of processing.
In many cases, Python's built-in container classes – list
, set
, or dict
– can cover the use cases. The small problem is that the syntax for a dictionary or a list isn't quite as elegant as the syntax for attributes of an object.
How can we create a class that allows us to use object.attribute
syntax instead of object['attribute']
?
Getting ready
There are two cases for any kind of class design:
- Is it stateless (immutable)? Does it embody attributes with values that never change? This is a good example of a
NamedTuple
. - Is it stateful (mutable)? Will there...