Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python's != operator think that arguments are equal and not equal at the same time?

Tags:

python

Take the following example:

>>> class C(object):
...     def __init__(self, p):
...         self.p = p
...     def __eq__(self, o):
...         return True
... 
>>> C(1) is C(2)
False
>>> C(1) == C(2)
True
>>> C(1) != C(2)
True # <- Why?!?

So now the two objects are equal and not-equal at the same time. I though the two operations are opposing?!

like image 975
Emil Ivanov Avatar asked Feb 11 '11 13:02

Emil Ivanov


People also ask

What does != equal in Python?

You can use "!= " and "is not" for not equal operation in Python. The python != ( not equal operator ) return True, if the values of the two Python operands given on each side of the operator are not equal, otherwise false .

What is == and != In Python?

Variables with the same value are often stored at separate memory addresses. This means that you should use == and != to compare their values and use the Python is and is not operators only when you want to check whether two variables point to the same memory address.

Why are there two equal signs in Python?

Difference between == and = in Python. In Python and many other programming languages, a single equal mark is used to assign a value to a variable, whereas two consecutive equal marks is used to check whether 2 expressions give the same value . (x==y) is False because we assigned different values to x and y.


2 Answers

Python’s “Data model” explains it all:

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 C(1) != C(2), it’s using the default implementation, where objects are equal only to themselves and unequal to everything else.

Defining __cmp__ can be simpler, as it is used as a fallback for all comparison operations, not just some of them:

...   def __cmp__(self, o):
...     return 0
>>> C(1) != C(2)
False
like image 101
Josh Lee Avatar answered Oct 15 '22 20:10

Josh Lee


There is a separate function for != which is __ne__ which is implicitly defined to compare the instance members.

What you want to do is:

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

or some variant of this.

like image 28
milkypostman Avatar answered Oct 15 '22 22:10

milkypostman