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
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.14 (GNU/Linux)
Comment: Using GnuPG with Mozilla -
http://enigmail.mozdev.org/
iQEcBAEBAgAGBQJQjsPoAAoJEAOzoR8eZTzgo2cH/jgg+Ht3FtDrAlswAV9P/pgo
nHahvG/FwLkrAwvJB/YE15SMv31XdrALu3BYqfzeOJOTmKZx/QUy8/HeMzOIqJak
/hwrvGOqDh+12CAhBI3jWiTup9jdROPkLonx31EmKy5EWgqKjTu SEbBZeKqXpxyX
SjHjXlGDup20FRYb+gTmsJfDqmyctq++JL9yfaBytgh/LzRhHPjaY/keRDo4f8S1
GRT00H7xrkGsmxpRrUG0T4sbRX1CQ2FtmHb7lrmR+gpDt2F5iw 6Cknx0Su5z6oFV
gx2tzDhJ0JbpjxQcukT68IUrCBPeSBRecxpZGoNPNoIIFLjnYI IKrsCrKroz7pY=
=QnP7
-----END PGP SIGNATURE-----