1

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,508
  • 1
  • 41
  • 52
hithwen
  • 2,154
  • 28
  • 46

2 Answers2

7

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
  • 141,790
  • 18
  • 296
  • 355
4

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
  • 244,495
  • 58
  • 464
  • 504
thefourtheye
  • 233,700
  • 52
  • 457
  • 497