dictionary keys, __hash__, __cmp__
Jan-Erik Meyer-Lütgens
python at meyer-luetgens.de
Wed Nov 5 10:10:40 EST 2003
Michael Hudson wrote:
> Jan-Erik Meyer-Lütgens <python at meyer-luetgens.de> writes:
>>Michael Hudson wrote:
>>>Jan-Erik Meyer-Lütgens <python at meyer-luetgens.de> writes:
>>>
>>>> 3. "If a class does not define a __cmp__() method it
>>>> should not define a __hash__() operation either."
>>>>
>>
>>Ok, let me ask the following question: What is the reason
>>for that rule?
>
>
> Well, the idea is that dictionary lookup is done by equality. If you
> don't define __cmp__ then equality is in fact identity (well, that's
> very nearly true...) so the default implementation of __hash__ (based
...and the full truth is? :-)
> on the pointer address) is as good as it can get (you have hash
> equality iff you have object equality).
>
> I think.
>
So, this rule is a hint, only. It could break performance,
not functionality, if I define my own hash function, right?
To make things totally clear, I repeat my question:
The only thing to be aware of when working with keys (besides
of object immutability) seems the following:
Keys are equivalent (in the sense of: a key inserted under
key1 can be retrieved with key2), if this is valid:
hash(key1) == hash(key2) and key1 == key2
Is this guaranteed? In future implementations?
--
Jan-Erik
More information about the Python-list
mailing list