So in python, truth conditions can be easily checked and with parenthesis it prioritize the order of true conditions, e.g. these are easy to understand:
>>> 3 > 2
True
>>> (3 > 2) is True
True
But what does these mean, I couldn't grasp the logic of why they return False/True:
>>> 3 > 2 is True
False
>>> 3 > (2 is True)
True
>>> 5 < 3 is False > 2 is True
False
>>> 5 < 3 is False is True > 2 is True
False
>>> 3 < 5 is True is True > 2 is True
False
>>> 3 < 5 is True is True > 2 is True is not False is True
False
>>> 3 < 5 is True is (True > 2 is True is not False) is True
False
>>> 3 < 5 is True is (True > (2 is True) is not False) is True
False
>>> (3 < 5 is True is True) > 2 is (True is not False is True)
False
I know these are not pythonic conditions but how should I understand them? Is it still from left to right?
Or does is True or/and is False takes presidence?
解决方案
You can analyse each of those cases with dis module to figure out exactly what's happening. For example:
In [1]: import dis
In [2]: def test():
...: return 3 > 2 is True
...:
In [3]: dis.dis(test)
2 0 LOAD_CONST 1 (3)
3 LOAD_CONST 2 (2)
6 DUP_TOP
7 ROT_THREE
8 COMPARE_OP 4 (>)
11 JUMP_IF_FALSE_OR_POP 21
14 LOAD_GLOBAL 0 (True)
17 COMPARE_OP 8 (is)
20 RETURN_VALUE
>> 21 ROT_TWO
22 POP_TOP
23 RETURN_VALUE
That means the stack looks like this after each step:
0: 3
3: 3 2
6: 3 2 2
7: 2 3 2
8: 2 True
11: 2
14: 2 True
17: False (comparison was: "2 is True")
20: (False is returned)
To me, it looks like a bug in Python to be honest. Maybe there's some good explanation of why this happens, but I'd report it upstream.
Just to rewrite it in equivalent way, the code does:
if 3 > 2:
if 2 is True:
return True
return False
Edit: Maybe it actually makes some weird kind of sense. Consider how checking chained inequalities works:
3 > 2 > 1 == 3 > 2 and 2 > 1
If it generalises to:
x op1 y op2 z == x op1 y and y op2 z
that would explain the result.
Edit2: This actually matches documentation. Have a look at chained comparisons: https://docs.python.org/2/reference/expressions.html#not-in
comparison ::= or_expr ( comp_operator or_expr )*
comp_operator ::= "" | "==" | ">=" | "<=" | "<>" | "!="
| "is" ["not"] | ["not"] "in"
is is considered just as good comparison as >, so the standard expansion for multiple comparisons is applied.
Other comparisons should be clear now. The only strange new detail needed is: True == 1, False == 0, so 3 > False in 3 > (2 is True). Most others can be explained with the expansions. For example:
5 < 3 is False > 2 is True == False
(5 < 3) and (3 is False) and (False > 2) and (2 is True) == False