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__
.
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.
== Equal to - True if both operands are equal. x == y. != Not equal to - True if operands are not equal.
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 !=
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.
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.
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 thatx!=y
is false. Accordingly, when defining__eq__()
, one should also define__ne__()
so that the operators will behave as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With