[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

immutability is not strictly the same as having an unchangeable value, it is more subtle

Arup Rakshit wrote:
> What protocols I need to
> learn, to define a custom immutable class ?

That depends on how strictly you want to enforce immutability.

The easiest thing is not to enforce it at all and simply refrain
from mutating it. This is very often done.

You can provide some protection against accidental mutation
by using properties, for example,

     class Foo:

         def __init__(self, x):
             self._x = x

         def x(self):
             return self._x

This will let you read the x attribute but not directly assign
to it. Of course, it doesn't prevent someone from accessing the
underlying _x attribute, but there's no way to do that for a
class defined in Python. The only way to make a completely
bulletproof immutable object would be to write an extension
module in C or Cython.