Why are tuples immutable?
Antoon Pardon
apardon at forel.vub.ac.be
Thu Dec 16 07:28:07 EST 2004
Op 2004-12-16, Fredrik Lundh schreef <fredrik at pythonware.com>:
> Antoon Pardon wrote:
>
>>> how does the dictionary know if you want key value equality or key
>>> identity equality?
>>
>> By the __hash__ and __eq__ methods you provide on your object.
>
> so what you're saying is that Python dictionaries should work just like
> Python dictionaries work today.
>
> sorry for wasting my time.
In the end yes. I was a bit confused at first because others were
asserting that python didn't allow mutable keys and gave reasons
for why they thought that was a good thing. I didn't know better
so originally just tried to argue why that would be a bad thing.
As it turns out those assertions were wrong.
Although the documentation on the python site does state this:
http://docs.python.org/lib/typesmapping.html
Only values containing lists, dictionaries or other mutable types
(that are compared by value rather than by object identity) may not be
used as keys.
And the following:
http://docs.python.org/ref/customization.html
If a class defines mutable objects and implements a __cmp__() or
__eq__() method, it should not implement __hash__(), since the
dictionary implementation requires that a key's hash value is
immutable (if the object's hash value changes, it will be in the wrong
hash bucket).
I find the latter to be misleading. The dictionary class probably
doesn't require that a key's hash value is immutable, just that a
key's hash value doesn't mutate during its lifecycle in the dictionary.
--
Antoon Pardon
More information about the Python-list
mailing list