Skip to content

Commit f1a7178

Browse files
committed
python#1920: when considering a block starting by "while 0", the compiler optimized the
whole construct away, even when an 'else' clause is present:: while 0: print("no") else: print("yes") did not generate any code at all. Now the compiler emits the 'else' block, like it already does for 'if' statements. Backport of r60265.
1 parent d933e0a commit f1a7178

3 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎Lib/test/test_grammar.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,15 @@ def f():
511511
while 0: pass
512512
else: pass
513513

514+
# Issue1920: "while 0" is optimized away,
515+
# ensure that the "else" clause is still present.
516+
x = 0
517+
while 0:
518+
x = 1
519+
else:
520+
x = 2
521+
assert x == 2
522+
514523
print 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
515524
for i in 1, 2, 3: pass
516525
for i, j, k in (): pass

‎Misc/NEWS‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ What's New in Python 2.5.2c1?
1212
Core and builtins
1313
-----------------
1414

15+
- Issue #1920: "while 0" statements were completely removed by the compiler,
16+
even in the presence of an "else" clause, which is supposed to be run when
17+
the condition is false. Now the compiler correctly emits bytecode for the
18+
"else" suite.
19+
1520
- A few crashers fixed: weakref_in_del.py (issue #1377858);
1621
loosing_dict_ref.py (issue #1303614, test67.py);
1722
borrowed_ref_[34].py (not in tracker).

‎Python/compile.c‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2256,8 +2256,11 @@ compiler_while(struct compiler *c, stmt_ty s)
22562256
basicblock *loop, *orelse, *end, *anchor = NULL;
22572257
int constant = expr_constant(s->v.While.test);
22582258

2259-
if (constant == 0)
2259+
if (constant == 0) {
2260+
if (s->v.While.orelse)
2261+
VISIT_SEQ(c, stmt, s->v.While.orelse);
22602262
return 1;
2263+
}
22612264
loop = compiler_new_block(c);
22622265
end = compiler_new_block(c);
22632266
if (constant == -1) {

0 commit comments

Comments
 (0)