Making immutable instances

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Nov 23 23:36:27 EST 2005


Alex Martelli <aleax at mail.comcast.net> wrote:
> Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
> > How can a (user-defined) class ensure that its instances are
> > immutable, like an int or a tuple, without inheriting from those
> > types?
> 
> You can make a good start by defining __setattr__, __delattr__ (and
> __setitem__ and __delitem__ if your class is a container) to raise
> exceptions.
> [...]
> Do not define any of the in-place operator special methods, such as
> __iadd__ and friends (or, if you're inheriting from a class that
> does define them, override them to raise exceptions).

That sounds more Pythonic than hacking __slots__.  Thanks.

> 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?

> You will probably want to define __hash__ and __eq__ if you're going
> to the trouble of making instances immutable.

Good tip, thanks.

-- 
 \       "I'm having amnesia and d?j? vu at the same time. I feel like |
  `\           I've forgotten this before sometime."  -- Steven Wright |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list