hash values and equality

Peter Otten __peter__ at web.de
Sat May 21 05:24:40 EDT 2011


Gregory Ewing wrote:

> Ethan Furman wrote:
>> Ulrich Eckhardt wrote:
>> 
>>> If two equal objects have different hashes, they
>>> will be stored in different places in the hash map. Looking for
>>> object1 will then not turn up with object2, even though they are equal.
>> 
>> In this case this is the behavior I want.
> 
> You can't rely on it, though. The hash value gets reduced
> modulo the size of the dict, so even if two objects have
> different hashes, in some cases they will land on the same
> dict slot anyway.
> 
> So an object such as you're postulating would behave
> unpredictably when used as a dict key. Sometimes a lookup
> using a different but equal object would find it, and
> sometimes not, seemingly at random.

I think for every potential match the current dict implementation checks 
identity, then hashes -- and equality only if the hash values are equal. The 
relevant function is lookdict() in dictobject.c.

While that means that the problem you describe cannot occur a simple 
approach that avoids relying on an implementation detail (?) would be to use 
(hash(obj), obj) tuples instead of just obj as the key.




More information about the Python-list mailing list