[Python-ideas] for/else syntax

Nick Coghlan ncoghlan at gmail.com
Fri Oct 2 13:16:50 CEST 2009

Steven D'Aprano wrote:
> And in fact, it is legal to have for loops without a break but include 
> an else. Is it useful? I don't know, but Python can't forbid them 
> without breaking (pun not intended) code like this:
> for x in xs:
>     if __debug__:
>         break
> else:
>     print "whatever"
> "if __debug__: suite" is special: the Python compiler optimizes the 
> entire suite away when running with the -O flag. So if Python would 
> treat the presence of an else as an error unless there was a break, you 
> could have some code which was, or wasn't, legal according to the 
> presence of the optimize flag. This is clearly a Bad Thing.
> Hence, even if for...else with no breaks are useless, they must be 
> allowed.

A SyntaxWarning should still be OK though - having an else clause that
can only be reached in debug mode is pretty dubious in its own right.


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

More information about the Python-ideas mailing list