[Python-ideas] for/else syntax

Nick Coghlan ncoghlan at gmail.com
Sat Oct 3 07:08:49 CEST 2009

Nick Coghlan wrote:
> Steven D'Aprano wrote:
>> On Fri, 2 Oct 2009 09:01:20 pm Nick Coghlan wrote:
>>> Yuvgoog Greenle wrote:
>>>> 1. Not allowing a for loop that has no "break" to have an "else".
>>>> Just like "else" isn't allowed when there isn't an "except" in the
>>>> "try". There really is no excuse, justification or sense in a "for"
>>>> loop that has no "break" yet has an "else".
>>> As Stephen said, that's a very good point. Having the compiler issue
>>> a SyntaxWarning when compiling such code is perfectly possible and
>>> would make a great deal of sense (and probably prevent many cases of
>>> naive misuse).
>> I disagree that it makes sense. Why raise a SyntaxWarning for legal 
>> code?
> Yeah, I was wrong. Definitely in pylint/pychecker territory.

After the additional posts in the discussion, I'm back to my previous
opinion - the construct should be referred to as break/else (or
for/break/else and while/break/else) and we should at least investigate
having the compiler itself raise at least a SyntaxWarning if it
encounters a for/else or while/else construct without also encountering
a break statement inside the loop.

The situation is *exactly* analagous to try/except/else: if there is no
except clause, then using the "else" is redundant - just put the code
inside the try block (if there is also a finally clause) or ditch the
try statement altogether (if there is no finally clause). The compiler
enforces this by treating try/else with no except clause as a SyntaxError.

For a loop with no break statements the else clause will *always* be
executed, hence using the clause is completely redundant - the code it
contains might as well be dedented and placed inline at the same level
as the loop header.


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

More information about the Python-ideas mailing list