On Mon, Oct 29, 2012 at 3:30 PM, Steven D'Aprano <steve+comp.lang.pyt...@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' -- http://mail.python.org/mailman/listinfo/python-list