hash values and equality
Ethan Furman
ethan at stoneleaf.us
Fri May 20 13:57:42 EDT 2011
Peter Otten 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? Here's a toy example of a class I'm thinking of writing
>> that will compare equal with int's, but hash differently:
>>
>> --> class Wierd():
>> ... def __init__(self, value):
>> ... self.value = value
>> ... def __eq__(self, other):
>> ... return self.value == other
>> ... def __hash__(self):
>> ... return hash((self.value + 13) ** 3)
>> ...
>
> Try this:
>
>>>> d = {Wierd(1): 0}
>>>> 1 in d
> False
>>>> 1 in d.keys()
> True
>
My apologies -- I'm trying this in Python3:
--> two in d
True
--> two in d.keys()
True
-->
--> 2 in d
True
--> 2 in d.keys()
True
~Ethan~
More information about the Python-list
mailing list