Making immutable instances

Giovanni Bajo noway at sorry.com
Thu Nov 24 00:36:59 CET 2005


Ben Finney wrote:

> How can a (user-defined) class ensure that its instances are
> immutable, like an int or a tuple, without inheriting from those
> types?
>
> What caveats should be observed in making immutable instances?


In short, you can't. I usually try harder to derive from tuple to achieve this
(defining a few read-only properties to access item through attributes). Using
__slots__ is then required to avoid people adding attributes to the instance.

In fact, I don't know the rationale. I would think it would be a great addition
to be able to say __immutable__ = True or something like that. Or at least, I'd
be grateful if someone explained me why this can't or shouldn't be done.
-- 
Giovanni Bajo





More information about the Python-list mailing list