Yesterday while going through some code with a coworker, we lost 5 minutes trying to find why 2 objects that looked the same where actually not evaluated equal. We did have the __eq__
method defined on the class, yet the comparison was evaluating to False
. Why?
Actually we were not testing for equality but for difference, so I thought: “hum, is ne required in this case?”. Actually it is. I felt stupid for not remembering it, but fortunately the Python documentation contained a great explanation:
There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining
__eq__()
, one should also define
__ne__()
so that the operators will behave as expected.
Lets see a quick example showing the failure, and hopefully remember it for the next time:
[gist]https://gist.github.com/1114589[/gist]
:wq