views:

98

answers:

2

As per the python documentation,x<y<z comparison is translated to x<y and y<z and expression y is evaluated only once at most.
Now my question is , does an expression y ( look at the code below) is evaluated only once here?

if(x<y and y<z):
+3  A: 

No:

>>> dis.dis(lambda x, y, z: x < y() < z)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 CALL_FUNCTION            0
              9 DUP_TOP             
             10 ROT_THREE           
             11 COMPARE_OP               0 (<)
             14 JUMP_IF_FALSE            8 (to 25)
             17 POP_TOP             
             18 LOAD_FAST                2 (z)
             21 COMPARE_OP               0 (<)
             24 RETURN_VALUE        
        >>   25 ROT_TWO             
             26 POP_TOP             
             27 RETURN_VALUE        
>>> dis.dis(lambda x, y, z: x < y() and y() < z)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 CALL_FUNCTION            0
              9 COMPARE_OP               0 (<)
             12 JUMP_IF_FALSE           13 (to 28)
             15 POP_TOP             
             16 LOAD_FAST                1 (y)
             19 CALL_FUNCTION            0
             22 LOAD_FAST                2 (z)
             25 COMPARE_OP               0 (<)
        >>   28 RETURN_VALUE        
Ignacio Vazquez-Abrams
+9  A: 

Twice:

>>> def f():
...   print "F called"
...   return 1
...
>>> 0 < f() < 100
F called
True
>>> 0 < f() and f() < 100
F called
F called
True
>>> if (0 < f() and f() < 100):
...   print True
...
F called
F called
True
>>>
MattH