hash values and equality

Peter Otten __peter__ at web.de
Fri May 20 02:38:30 EDT 2011


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




More information about the Python-list mailing list