[Python-ideas] SyntaxWarning for for/while/else without break or return?

Nick Coghlan ncoghlan at gmail.com
Thu Oct 8 12:19:06 CEST 2009

Yuvgoog Greenle wrote:
> So the only way to the "else" clause is useful is when a "break" can
> skip it. If there is no "break", you might as well remove the "else" and
> deindent.


As to the original question in this thread - definitely possible, and
shouldn't be particularly difficult.

The AST and the symbol table generation don't really keep track of loop
nesting (as they don't care all that much), so you would defer picking
this situation up to the actual compilation stage (Python/compile.c in
the source tree).

Conveniently, the compiler already searches for a LOOP fblock in order
to generate the syntax error for using break outside a loop, so adding a
"fb_break" field to the fblock struct would be a simple way to keep
track of whether or not a loop contains a break statement (although I
suspect you would have to reverse the current fblock search order to
find the innermost loop instead of the outermost one).

Then in compiler_for and compiler_while, the fb_break field on the
relevant LOOP fblock could be checked whenever an OrElse clause was
present in the AST. A SyntaxWarning would then be emitted whenever the
else clause was present but the break flag was not set on the relevant
LOOP fblock.

That's just an implementation sketch obviously, and not actually tested
in any way shape or form. Still, it should be fairly straightforward to
add the warning.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list