Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a not equal operator in python [duplicate]

I was wondering about the reason of having a not equal operator in python.

The following snipped:

class Foo:
    def __eq__(self, other):
        print('Equal called')
        return True

    def __ne__(self, other):
        print('Not equal called')
        return True

if __name__ == '__main__':
    a = Foo()

    print(a == 1)
    print(a != 1)
    print(not a == 1)

outputs:

Equal called
True
Not equal called
True
Equal called
False

Doesn't this actually invite a lot of trouble by potentially saying:

A == B and A != B

can be correct at the same time. Furthermore this introduces a potential pitfall when forgetting to implement __ne__.

like image 688
magu_ Avatar asked Jun 11 '15 17:06

magu_


People also ask

Why do we use != In Python?

Not Equal Operator in Python If the values compared are equal, then a value of true is returned. If the values compared are not equal, then a value of false is returned. != is the symbol we use for the not equal operator.

What is == and != In Python?

== Equal to - True if both operands are equal. x == y. != Not equal to - True if operands are not equal.

What double == means in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=

Can you do != In Python?

In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Note: It is important to keep in mind that this comparison operator will return True if the values are same but are of different data types.


2 Answers

Depending on one's needs there are cases where equal and not equal are not opposite; however, the vast majority of cases they are opposite, so in Python 3 if you do not specify a __ne__ method Python will invert the __eq__ method for you.

If you are writing code to run on both Python 2 and Python 3, then you should define both.

like image 141
Ethan Furman Avatar answered Oct 05 '22 02:10

Ethan Furman


Per the data model documentation, which covers the "magic methods" you can implement on classes (emphasis mine):

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.

like image 32
jonrsharpe Avatar answered Oct 05 '22 02:10

jonrsharpe