Immutability and Python
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Oct 29 18:30:40 EDT 2012
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.
See the source code for collections.namedtuple and decimal.Decimal for
some examples.
Warning: namedtuple is special, because it uses some runtime exec magic;
most immutable classes do not need that. And Decimal is seriously large
and complicated. But you can get some ideas from them both.
Also, see this:
http://northernplanets.blogspot.com.au/2007/01/immutable-instances-in-python.html
--
Steven
More information about the Python-list
mailing list