Immutability and Python

Evan Driscoll driscoll at cs.wisc.edu
Mon Oct 29 13:58:58 EDT 2012


On 10/29/2012 12:05 PM, 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..

The short answer is: you don't, not really, except by using NamedTuple
if that gives you what you want.

The longer answer:

You can kinda get it somewhat if you define your own
__getattribute__/__setattribute__ functions. __setattribute__ of course
should never do anything except raise an error (one way or another
you'll need to make an exception for your __init__ function of course).
__getattribute__ should make sure no mutable references are returned:
e.g. you'll probably want to make it so someone can't side-step your
setter by saying someobject.__dict__["foo"] = "bar". (I return a copy of
the dict.) It will still be possible to bypass these protections though.

To really get true immutability in pure Python, you'll have to inherit
from tuple or NamedTuple (which inherits from tuple, I think). You can
see some discussion on Stack Overflow and some other places about this;
having played around with this a bit, I think it's not worth the hassle
and have done the __getattribute__/__setattribute__ thing the couple of
times I wanted immutability.

Evan

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 554 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20121029/dd4667a6/attachment.sig>


More information about the Python-list mailing list