Odd Operator Precedence/associativity Behaviour
How is it that, in Python 2.7, the following True == 'w' in 'what!?' behaves differently than both (True == 'w') in 'what!?' and True == ('w' in 'what!?') ? >>> True ==
Solution 1:
In Python, comparisons can be chained together:
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
So your code is actually equivalent to
>>> (True == 'w') and ('w'in'what!?')
False
Solution 2:
Let's take a look:
>>>import ast>>>ast.dump(ast.parse("""True == 'w' in 'what!?'""", mode='eval'))
"Expression(body=Compare(left=Name(id='True', ctx=Load()), ops=[Eq(), In()],
comparators=[Str(s='w'), Str(s='what!?')]))"
This is a chained comparison:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once [...]
Post a Comment for "Odd Operator Precedence/associativity Behaviour"