Making immutable instances

Scott David Daniels scott.daniels at
Thu Nov 24 14:00:25 CET 2005

Ben Finney wrote:
> Alex Martelli <aleax at> wrote:
>>Ben Finney <bignose+hates-spam at> wrote:
>>>How can a (user-defined) class ensure that its instances are
>>>immutable, like an int or a tuple, without inheriting from those
>>You can make a good start by defining __setattr__, __delattr__ (and
>>__setitem__ and __delitem__ if your class is a container) to raise
>>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
> _FooFunctionality class, and then inherit from that to make Foo as the
> immutable class that actually gets exported?

Typically, constants are set up in __new__ (which happens before
__init__), because by __init__ time the object is built.  Remember
not to complain that you have no copy operation, because there is no
such thing as a copy of a constant (the original constant is good

--Scott David Daniels
scott.daniels at

More information about the Python-list mailing list