S
Steven D'Aprano
Dennis said: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@ando ~]$ python2.7 -c "from dis import dis
1 0 SETUP_LOOP 35 (to 38)code = compile('''\
for x in [1, 2, 3]:
pass
else:
assert x
''', '', 'exec')
dis(code)"""
3 LOAD_CONST 0 (1)
6 LOAD_CONST 1 (2)
9 LOAD_CONST 2 (3)
12 BUILD_LIST 3
15 GET_ITER19 STORE_NAME 0 (x)
2 22 JUMP_ABSOLUTE 16
4 26 LOAD_NAME 0 (x)
29 POP_JUMP_IF_TRUE 38
32 LOAD_GLOBAL 1 (AssertionError)
35 RAISE_VARARGS 141 RETURN_VALUE
Compare to the case with optimizations on:
[steve@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_ITER19 STORE_NAME 0 (x)
2 22 JUMP_ABSOLUTE 16
4 >> 26 LOAD_CONST 3 (None)
29 RETURN_VALUE