Python Operator Priority - and More Than

I have a line of code in my script in which both of these statements are connected together. From the documentation help, BOOLEAN AND has a lower priority than COMPARING MORE . I get unexpected results here in this code:

>>> def test(msg, value): ... print(msg) ... return value >>> test("First", 10) and test("Second", 15) > test("Third", 5) First Second Third True 

I expected the second or third test to happen before the first, since the > operator has a higher priority. What am I doing wrong here?

https://docs.python.org/3/reference/expressions.html#operator-precedence

+6
source share
2 answers

Because you are not looking at anything. call (or function call) has higher accuracy for both and , as well as > (more). Therefore, the first function calls occur from left to right.

Python will get results for all function calls before the comparison happens. The only thing that needs attention here is a short circuit, so if test("First",10) returns False, it will be a short circuit and return False.

Comparison and and still occur with the same accuracy as the result of test("Second", 15) compared with test("Third", 5) (pay attention only to the return values ​​(the function call was previously called)). Then the result of test("Second", 15) > test("Third", 5) used in the and operation.

From the documentation on operator priority -

enter image description here

+7
source

One way to see what happens is to see how exactly Python interprets this result:

 >>> x = lambda: test("First", 10) and test("Second", 15) > test("Third", 5) >>> dis.dis(x) 1 0 LOAD_GLOBAL 0 (test) 3 LOAD_CONST 1 ('First') 6 LOAD_CONST 2 (10) 9 CALL_FUNCTION 2 12 JUMP_IF_FALSE_OR_POP 42 15 LOAD_GLOBAL 0 (test) 18 LOAD_CONST 3 ('Second') 21 LOAD_CONST 4 (15) 24 CALL_FUNCTION 2 27 LOAD_GLOBAL 0 (test) 30 LOAD_CONST 5 ('Third') 33 LOAD_CONST 6 (5) 36 CALL_FUNCTION 2 39 COMPARE_OP 4 (>) >> 42 RETURN_VALUE 

If you do the same for 10 and 15 > 5 , you will get:

 >>> x = lambda: 10 and 15 > 5 >>> dis.dis(x) 1 0 LOAD_CONST 1 (10) 3 JUMP_IF_FALSE_OR_POP 15 6 LOAD_CONST 2 (15) 9 LOAD_CONST 3 (5) 12 COMPARE_OP 4 (>) >> 15 RETURN_VALUE 
+3
source

All Articles