Making immutable instances

Mike Meyer mwm at
Thu Nov 24 01:18:32 CET 2005

"Giovanni Bajo" <noway at> 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 Meyer <mwm at>
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list