hash values and equality
Peter Otten
__peter__ at web.de
Fri May 20 16:25:27 EDT 2011
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__
>>>
>>> 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:
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
More information about the Python-list
mailing list