Home >Backend Development >Python Tutorial >How Can We Achieve True Immutability in Python?
Making Immutable Objects in Python
Creating immutable objects in Python can pose challenges. Simply overriding setattr is insufficient, as attributes cannot be set during initialization. A commonly employed solution is to subclass a tuple, as demonstrated below:
<code class="python">class Immutable(tuple): def __new__(cls, a, b): return tuple.__new__(cls, (a, b)) @property def a(self): return self[0] @property def b(self): return self[1] def __str__(self): return "<Immutable {0}, {1}>".format(self.a, self.b) def __setattr__(self, *ignored): raise NotImplementedError def __delattr__(self, *ignored): raise NotImplementedError</code>
However, this approach grants access to the a and b attributes through self[0] and self[1], which can be inconvenient.
To achieve pure Python immutability, another alternative exists:
<code class="python">Immutable = collections.namedtuple("Immutable", ["a", "b"])</code>
This method generates a type with the desired behavior, utilizing slots and inheriting from tuple. It offers the benefits of compatibility with pickle and copy, but still allows for accessing attributes via [0] and [1].
The above is the detailed content of How Can We Achieve True Immutability in Python?. For more information, please follow other related articles on the PHP Chinese website!