hash values and equality
Ethan Furman
ethan at stoneleaf.us
Fri May 20 14:38:41 EDT 2011
Ulrich Eckhardt wrote:
> Ethan Furman wrote:
>> Several folk have said that objects that compare equal must hash equal,
>> and the docs also state this
>> http://docs.python.org/dev/reference/datamodel.html#object.__hash__
>>
>> I'm hoping somebody can tell me what horrible thing will happen if this
>> isn't the case?
>
> If you were familiar with what a hash map is, you wouldn't ask. The thing is
> that the hash is used to look up the place in the map where the thing is
> stored. 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.
> If this is something you don't
> care about, and all you care about is identity, then I'd derive the hash
> from each object's ID.
This won't work, as objects of the same type that compare equal should
(and do, in my code) hash equal.
> This ID has another property which is something that is assumed for hashes,
> and your code seems a bit to get that wrong, too, and that is that the hash
> must not change.
The hash does not change on the instances, and is the same for all
instances of my type that compare equal.
~Ethan~
More information about the Python-list
mailing list