hash values and equality

Ethan Furman ethan at stoneleaf.us
Fri May 20 17:48:27 EDT 2011


Peter Otten wrote:
> Ethan Furman wrote:
> 
>> 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__
>>>>
>>>> --> 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:
> 
> Then you have to convert the keys to a list explicitly:
> 
>>>> class Weird:
> ...     def __init__(self, value):
> ...             self.value = value
> ...     def __eq__(self, other):
> ...             return self.value == other
> ...     def __hash__(self):
> ...             return hash((self.value + 13) **3)
> ...
>>>> d = {Weird(1): 0}
>>>> 1 in d
> False
>>>> 1 in d.keys()
> False
>>>> 1 in list(d.keys())
> True

Ah!!  The light finally dawned!  Many thanks for everyone's input.

So if Wierd has a need to compare equal to some other type, it should 
implement a .equals() method.  Gotcha.

Likewise, if two different type's instances can compare equal, then for 
the most part they should be interchangeable.

~Ethan~



More information about the Python-list mailing list