Rich comparison methods don't work in sets?

Steven D'Aprano steve at REMOVETHIS.cybersource.com.au
Sat Jun 20 18:13:04 CEST 2009


Gustavo Narea wrote:

> Hello again, everybody.
> 
> Thank you very much for your responses. You guessed right, I didn't
> use the __hash__ method (and I forgot to mention that, sorry).
> 
> And unfortunately, I think I can't make them hashable, because the
> objects are compared based on their attributes, which are in turn
> other kind of objects compared based on other attributes. All these
> class instances are compared with __eq__/__ne__ and they wrap
> relatively complex data which would be hard to attempt to represent
> them unambiguously using a 32-bit integer.

There is no need for hash to represent the data unambiguously.

>>> hash(-1)
-2
>>> hash(-2)
-2
>>> hash(2.0**32 - 1)
-2


>>> hash(1)
1
>>> hash(2.0**64 - 1)
1
>>> hash(2.0**64 + 1)
1


>>> hash(2)
2
>>> hash(1+2**32)
2
>>> hash(1+2**64)
2
>>> hash(1+2**128)
2
>>> hash(2.0)
2



The rule is, if x and y are equal, then hash(x) should equal hash(y). This
does NOT imply that if hash(x) == hash(y), then x must equal y, nor is
there any requirement for every unique piece of data to have a unique hash.



-- 
Steven




More information about the Python-list mailing list