LoveOfLearning
LoveOfLearning

Reputation: 215

Why is it possible to override both __eq__ and __ne__ in classes?

Python provides the feature of overloading == operator AND != operator. But, why? Isn't it enough to overload == and != is automatically the opposite (in truth value) of ==?

Shouldn't the result of one imply the other automatically?

Upvotes: 2

Views: 270

Answers (1)

cs95
cs95

Reputation: 402892

You don't have to, python isn't forcing you to. In fact, the documentation explains the what and why:

By default, __ne__() delegates to __eq__() and inverts the result unless it is NotImplemented. There are no other implied relationships among the comparison operators, for example, the truth of (x<y or x==y) does not imply x<=y.

In general, the truth of x==y does not have need to imply that x!=y is false. If your data model needs to reflect this relationship, python lets you do so with minimal headache.

Note that for earlier versions of python, not even this relationship was implied. For example,

class Foo:
    def __init__(self, val):
        self.val = val

    def __eq__(self, other):
        return self.val == other.val

f1, f2 = Foo(1), Foo(1)

Now, f1 == f2 returns True on any version. HOWEVER, f1 != f2 returns False on python-3.x, but True on python-2.x (because __ne__ is not implied on python-2.x, and in general two user defined objects are not equal if their IDs are not the same, i.e., not the same object).

Upvotes: 6

Related Questions