Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does operator binding work in this Python example?

I've recently stumbled over this expression:

True == False in (False,)

It evaluates to False, but I don't understand why. True == False is False and False in (False,) is True, so both (to me) plausible possibilities

True == (False in (False,))

and

(True == False) in (False,)

evaluate to True, as I would have expected. What is going wrong here?

like image 615
Turion Avatar asked Mar 27 '12 12:03

Turion


People also ask

What is operator precedence give one example of it?

Operator Precedence ¶ The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.


1 Answers

I believe this is a corner case of Python's comparison-operator chaining. It gets expanded to

 (True == False) and (False in (False,))

which evaluates to False.

This behavior was intended to match conventional math notation (e.g. x == y == z meaning that all three are equal, or 0 <= x < 10 meaning x is in the range [0, 10)). But in is also a comparison operator, giving the unexpected behavior.

like image 179
Mechanical snail Avatar answered Sep 21 '22 00:09

Mechanical snail