Re: Making immutable instances
- From: aleax@xxxxxxxxxxxxxxxx (Alex Martelli)
- Date: Wed, 23 Nov 2005 19:11:53 -0800
Ben Finney <bignose+hates-spam@xxxxxxxxxxxxxxx> 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. 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
trifling one.
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.
Alex
.
- Follow-Ups:
- Re: Making immutable instances
- From: Ben Finney
- Re: Making immutable instances
- From: Ben Finney
- Re: Making immutable instances
- References:
- Making immutable instances
- From: Ben Finney
- Making immutable instances
- Prev by Date: Re: wxPython Licence vs GPL
- Next by Date: Re: about sort and dictionary
- Previous by thread: Re: Making immutable instances
- Next by thread: Re: Making immutable instances
- Index(es):