[Tutor] equality check difference

Peter Otten __peter__ at web.de
Sat Apr 19 23:48:00 CEST 2014

```Vipul Sharma wrote:

> Hello,
>
> Suppose we want some block of code to be executed when both '*a'* and
> '*b'*are equal to say 5. Then we can write like :
>
> *if a == 5 and b == 5:*
> *    # do something*
>
> But a few days ago, I just involuntarily wrote a similar condition check
> as
> :
>
> *if a == b and b == 5:*
> *    # do something *
>
> which made me think, is there any difference between the two ?
>
> Is there any difference, any difference in the process of evaluation or
> execution ? and also which one is the better ?
>
> I think this is a general programming question and not specifically for
> python.
>
> P.S. : Newbie here :)

In mathematics there is a property called "transitivity" which basically
says that an operation op is transitive if from

(a op b) and (a op c)

follows

b op c

Integer equality is such an operation, and this holds for Python, too. If a
and b are integers you can safely assume that both conditions are
equivalent. There is even a third way to spell this:

if a == b == 5:
...

But for arbitrary objects transitivity is not guaranteed, and you may see
different outcomes. Here is a simple class that implements non-transitive
equality:

>>> class A:
...     def __eq__(self, other):
...             return isinstance(other, int)
...
>>> a = A()
>>> b = A()
>>> if a == 5 and b == 5:
...     print("yes")
... else:
...     print("no")
...
yes
>>> if a == b and b == 5:
...     print("yes")
... else:
...     print("no")
...
no

When you write a == b Python under the hood translates that to
a.__eq__(b), and when you implement your own __eq__() method you are free to
do anything you like. You can even vary the output between calls:

>>> import random
>>> class B:
...     def __eq__(self, other):
...             return random.choice([True, False])
...
>>> c = B()
>>> c == 42
False
>>> c == 42
False
>>> c == 42
True
>>> c == 42
False
>>> c == 42
True

Of course nobody (I hope) would recommend that you actually write such code.

PS: Can you guess what a == a prints?

```