cascading python executions only if return code is 0

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Dec 23 18:13:19 CET 2013


Dennis Lee Bieber wrote:

> On Mon, 23 Dec 2013 13:33:08 +1100, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> declaimed the following:
> 
>>Roy Smith wrote:
>>
>>
>>>         else:
>>>             assert 0, "can't create picker (classes = %s)" % classes
>>
>>¡Ay, caramba! I was with you until the very last line. The above code is
>>possibly buggy and inappropriately designed. (I may be completely
>>misinterpreting this, in which case feel free to ignore the following
>>rant.)
>>
> 
> I'd think the biggest problem with this is that if one runs Python with
> optimization turned on, the assert statement itself vanishes, leaving one
> with an empty else clause...
> 
> Try debugging that problem!


Actually, that's not correct. If the assert statement vanishes, so does the
else clause, since there's nothing in it.


[steve at ando ~]$ python2.7 -c "from dis import dis
> code = compile('''\
> for x in [1, 2, 3]:
>     pass
> else:
>     assert x
> ''', '', 'exec')
> dis(code)"""
  1           0 SETUP_LOOP              35 (to 38)
              3 LOAD_CONST               0 (1)
              6 LOAD_CONST               1 (2)
              9 LOAD_CONST               2 (3)
             12 BUILD_LIST               3
             15 GET_ITER
        >>   16 FOR_ITER                 6 (to 25)
             19 STORE_NAME               0 (x)

  2          22 JUMP_ABSOLUTE           16
        >>   25 POP_BLOCK

  4          26 LOAD_NAME                0 (x)
             29 POP_JUMP_IF_TRUE        38
             32 LOAD_GLOBAL              1 (AssertionError)
             35 RAISE_VARARGS            1
        >>   38 LOAD_CONST               3 (None)
             41 RETURN_VALUE


Compare to the case with optimizations on:


[steve at ando ~]$ python2.7 -O -c "from dis import dis
code = compile('''\
for x in [1, 2, 3]:
    pass
else:
    assert x
''', '', 'exec')
dis(code)"""
  1           0 SETUP_LOOP              23 (to 26)
              3 LOAD_CONST               0 (1)
              6 LOAD_CONST               1 (2)
              9 LOAD_CONST               2 (3)
             12 BUILD_LIST               3
             15 GET_ITER
        >>   16 FOR_ITER                 6 (to 25)
             19 STORE_NAME               0 (x)

  2          22 JUMP_ABSOLUTE           16
        >>   25 POP_BLOCK

  4     >>   26 LOAD_CONST               3 (None)
             29 RETURN_VALUE





-- 
Steven




More information about the Python-list mailing list