Making immutable instances
aleax at mail.comcast.net
Thu Nov 24 04:11:53 CET 2005
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
You can make a good start by defining __setattr__, __delattr__ (and
__setitem__ and __delitem__ if your class is a container) to raise
exceptions. Of course, these restrictions can be easily worked around
by a sufficiently determined attacker... but if you have to think of the
user of your code as an attacker, you've got worse problems than this
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).
> What caveats should be observed in making immutable instances?
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).
You will probably want to define __hash__ and __eq__ if you're going to
the trouble of making instances immutable.
More information about the Python-list