0

This is probably very basic but:

Being X and Y objects of the same class, invoking not x == y would cause my debugger to stop in class __eq__ method but invoking x != y would not?

What does != check? Is it equivalent to is not (reference checking)?

zakinster
  • 10,147
  • 1
  • 37
  • 50
hithwen
  • 2,113
  • 27
  • 46

2 Answers2

8

The != operator invokes the __ne__ special method. Classes that define __eq__ should also define a __ne__ method that does the inverse.

The typical pattern for providing __eq__, __ne__, and __hash__ looks like this:

class SomeClass(object):
    # ...
    def __eq__(self, other):
        if not isinstance(other, SomeClass):
            return NotImplemented
        return self.attr1 == other.attr1 and self.attr2 == other.attr2

    def __ne__(self, other):
        return not (self == other)

    # if __hash__ is not needed, write __hash__ = None and it will be
    # automatically disabled
    def __hash__(self):
        return hash((self.attr1, self.attr2))
user4815162342
  • 124,516
  • 15
  • 228
  • 298
5

Quoting from this page, http://docs.python.org/2/reference/datamodel.html#object.ne

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. See the paragraph on __hash__() for some important notes on creating hashable objects which support custom comparison operations and are usable as dictionary keys.

Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
thefourtheye
  • 221,210
  • 51
  • 432
  • 478