__eq__ and __ne__

Shane Hathaway shane at zope.com
Tue Jul 8 11:15:44 EDT 2003


I was surprised by the following behavior.  Apparently, the "!=" 
operator does not fall back to using "not __eq__()".  I tested this with 
Python 2.1, 2.2, and 2.2 with new-style classes and got the same results 
in every case.

 >>> class foo:
...     def __eq__(self, other):
...         return (other.__class__ is self.__class__
...                 and other.__dict__ == self.__dict__)
...
 >>> foo() == foo()
1
 >>> foo() != foo()
1

I would expect the second test to yield "0".  To compensate, I've 
started adding the following boilerplate code to all classes that define 
only __eq__:

def __ne__(self, other):
     return not self.__eq__(other)

Does this surprise anyone else?  I have not yet found documentation on this.

Shane






More information about the Python-list mailing list