Why are tuples immutable?
roy at panix.com
Fri Dec 17 21:31:24 CET 2004
Jeff Shannon <jeff at ccvcorp.com> wrote:
> The aesthetic purity I'm referring to is that Python respects the proper
> meaning of hashing, even if it doesn't force the programmer to. The
> builtin objects that Python provides don't offer a __hash__() method
> that fails to meet the mathematical prerequisites of a proper hash
> function -- that is, objects that are equal will hash identically. In
> addition, dictionaries expect keys to have proper hashing semantics,
> such that a given object's hash value will not change over its
> lifetime. It is not possible for a mutable object to satisfy both
> aspects of proper hashing behavior, therefore Python does not pretend
> that mutable objects are hashable.
If you look back over this thread, I've given several examples of
mutable objects which meet your requirements:
* Objects that are equal hash the same.
* Hash value does not change over the lifetime of the object.
All that's needed is to define __hash__() and __cmp__() methods which
only look at some subset of the object's data atrributes. You can
keep those attributes constant (perhaps enforced with __setattr__()
hooks) and let others mutate.
To be honest, I've never found a real-life need to do this. I often
want to use user-defined classes as keys, but it's just plain easier
to build tuples of that attribute subset on the fly than to build all
the required methods to make it work in-place. If memory was tight,
it might be worthwhile to avoid creating all those extra tuples, but
so far I havn't been faced with that.
I agree that saying "dictionary keys must be immutable" is a
reasonable simplification which works fine the vast majority of the
time. I would not, however, go as far as saying, "It is not possible
for a mutable object to satisfy both aspects of proper hashing
More information about the Python-list