Making immutable instances

Alex Martelli aleax at
Thu Nov 24 05:44:08 CET 2005

Ben Finney <bignose+hates-spam at> wrote:
> > Remember that your redefined __setattr__ IS "in place" even when
> > you're initializing your istance, so remember to delegate attribute
> > setting to the superclass (the other special methods mentioned above
> > are less likely to byte you).
> So, for a class that needs to set attributes in __init__ (but after
> that, become immutable), how do I get around this? Should I make a

As I said, you delegate attribute setting to the superclass.  E.g:

>>> class Immut(object):
...   def __setattr__(*a): raise TypeError, 'immutable'
...   def __init__(self, v=23):
...     super(Immut,self).__setattr__('v', v)
>>> x=Immut()
>>> x.v
>>> x.v=42
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in __setattr__
TypeError: immutable


More information about the Python-list mailing list