Creating immutable data classes in Python with namedtuple
I was reviewing some Python code at work today, in which we wanted to wrap up a number of fields in a simple immutable data class. Our initial attempt was to construct a long-winded class definition, for example:
Our real-world class had many more properties than the example above, and during the review, I did wonder whether there was a more elegant way of expressing this. After I bit of research, I eventually found collections.namedtuple
. This function can be used to construct a new class type, which has the same semantics as a tuple, but provides access to its members by name rather than by index. Using this function, the above class can be expressed as follows:
The class type returned by collections.namedtuple
can be used in exactly the same way as in the first example:
One notable difference between the two versions of this class type is that with namedtuple, you aren’t allowed to set a non-existant property either. This is presumably such that the namedtuple matches the semantics of a plain tuple: