Easy immutability in python?
Terry Hancock
hancock at anansispaceworks.com
Sat Mar 4 12:52:59 EST 2006
Is there an *easy* way to make an object immutable in
python? Or perhaps I should say "one obvious way to do it"?
Oughtn't there to be one?
I've found a thread on how to do this[1], which essentially
says something like "redefine __setattr__, __delattr__,
__hash__, __eq__, __setitem__, delitem__ ... and probably
some other stuff too".
[1]
Yet, what you have to do is pretty mechanical (e.g. all the
mutators have to raise NotImplementedError and the hashes
and comparisons seem like they have obvious defaults).
Given that I have some kind of container, like an overloaded
list, and I just say "oh, I need that to be immutable, like
a tuple" -- it would be nice to just be able to declare it
so. I just want this for QA purposes -- I have a pretty
complex system, and I want the programmer to be warned when
he accidentally tries to change an immutable enumeration or
redefine a symbol.
I know a (hard and error-prone) way to do it, but I'm
thinking there must be a "smart" way to do it.
Is there some way to do that with, e.g. decorators?
(I haven't really figured out why I should want decorators,
is this a use case?).
Or maybe I should make an "Immutable" class, and just
inherit from it last so it overloads everything else with
the null interfaces?
--
Terry Hancock (hancock at AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com
More information about the Python-list
mailing list