Immutability and Python

Chris Kaynor ckaynor at zindagigames.com
Mon Oct 29 18:45:59 EDT 2012


On Mon, Oct 29, 2012 at 3:30 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Mon, 29 Oct 2012 17:05:07 +0000, andrea crotti wrote:
>
>> I meant how do I create new immutables classes myself, I guess that's
>> possible writing C extensions but I don't see in pure Python..
>
> Well, you can't *quite* make a truly immutable class in pure-Python,
> because if *your* Python code can manipulate the class during
> construction then so can the caller's Python code after construction.
>
> The trivial way to make an immutable class in Python is to inherit from
> an already immutable class and add behaviour but no state:
>
> class MyInt(int):
>     def inc(self):
>         return self.__class__(self + 1)
>
>
> Otherwise, you can add private state and rely on the caller not shooting
> themselves in the foot by accessing single-underscore names, use
> properties to protect private state, etc.
>

You'd also need to add __slots__ = () to the class definition to make
it immutable. Otherwise they still can shoot themselves in the foot by
adding new attributes.

>>> class MyInt(int):
...    def inc(self):
...            return self.__class__(self+1)
...
>>> a = MyInt()
>>> a.b = 1 # Oops. Mutated "a".
>>> a.b
1



>>> class MyInt(int):
...     __slots__ = ()
...     def inc(self):
...             return self.__class__(self + 1)
...
>>> a = MyInt()
>>> a.b = 1
AttributeError: 'MyInt' object has no attribute 'b'
Traceback (most recent call last):
  File "<stdin-inspect>", line 1, in <module>
AttributeError: 'MyInt' object has no attribute 'b'



More information about the Python-list mailing list