Making immutable instances

Mike Meyer mwm at mired.org
Wed Nov 23 19:18:32 EST 2005


"Giovanni Bajo" <noway at sorry.com> writes:
> 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.

Note that this property of __slots__ is an implementation detail. You
can't rely on it working in the future.

I'm curious as to why you care if people add attributes to your
"immutable" class. Personally, I consider that instances of types
don't let me add attributes to be a wart.

      <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list