Why are tuples immutable?
Jeff Shannon
jeff at ccvcorp.com
Fri Dec 17 13:49:23 EST 2004
Antoon Pardon wrote:
>Op 2004-12-17, Jeff Shannon schreef <jeff at ccvcorp.com>:
>
>
>
>>(And I have to reiterate, here, that I have *never* felt it a hardship
>>to be unable to use lists as dictionary keys; it's just never come up
>>that the data that I had in a list was something that I wanted to use
>>as-is for a dict key, and I can't think of a situation where it *would*
>>happen. What you're saying, essentially, is that for the sake of one
>>form of aesthetic purity with no significant practical benefits, we
>>should break another form of aesthetic purity with massive practical
>>benefits.)
>>
>>
>[...]
>Besides python doesn't provide such an aesthetic purity. Even if
>it was true that only immutables could be used as keys in dictionaries
>there are other times some invariant is established or depended upon
>and yet python doesn't enforce immutable objects in those cases.
>So much of the aesthetic purity python provides.
>
>
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. Python does provide features that
allow you to define your own __hash__() on your own classes, and it has
no way of forcing you to make that a *proper* hash function, which
allows you to subvert things and create pseudo-hashable mutable objects,
but Python declines to do that itself -- it'll give you the rope to hang
yourself with, but it's not tying the noose.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list