Falmarri Falmarri - 6 months ago 31
Python Question

Python, should I implement __ne__() operator based on __eq__?

I have a class where I want to override the

operator. It seems to make sense that I should override the
operator as well, but does it make sense to implement
based on
as such?

class A:
def __eq__(self, other):
return self.value == other.value

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

Or is there something that I'm missing with the way Python uses these operators that makes this not a good idea?


Yes, that's perfectly fine. In fact, the documentation urges you to define __ne__ when you define __eq__:

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.

In a lot of cases (such as this one), it will be as simple as negating the result of __eq__, but not always.