How to make an immutable instance

Leif K-Brooks eurleif at
Fri Jun 18 01:00:16 CEST 2004

Batista, Facundo wrote:
> So, if you use this "immutable" class in a dict, and then you (on purpose)
> modify it, you'll have different hashes.
> Said that, how safer is this approach? Is there a better way?

The best I know of is this:

class Foo(object):
     __slots__ = ('x',)

     # __new__ is used instead of __init__ so that no one can call
     # __new__ directly and change the value later.
     def __new__(cls, value):
         self = object.__new__(cls)
         self.x = value
         return self

     def __setattr__(self, attr, value):
         if attr in self.__slots__ and not hasattr(self, attr):
             object.__setattr__(self, attr, value)
             raise AttributeError, "This object is immutable."

But note that you can still use object.__setattr__ directly to get 
around it. I don't think there's a way to get true immutability in pure 

More information about the Python-list mailing list