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

Nick Coghlan ncoghlan at gmail.com
Sat Oct 10 14:02:35 CEST 2009


Jacob Holm wrote:
> If I understand Nick correctly, this is irrelevant.  The warning/error
> generation would be handled by an earlier stage than the optimization
> that removes the break.

I never promised that - someone else said that would happen, but it's
actually implementation dependent.

In the case of CPython, the compiler stage checks for recognised
constants (such as 0, non-zero integers, True, False and __debug__) in
if statement test expressions and doesn't even bother visiting any
unreachable code.

Accordingly, Steven is quite correct that having your only break
statement inside "if __debug__:" would lead to the natural
implementation approach for CPython issuing a SyntaxWarning when running
under the optimiser.

Make no mistake, the whole point of adding this warning would be to
cause some currently legal code to generate a warning. It would be a
policy decision, stating that "for/break/else" and "while/break/else"
were the only accepted use cases for the else clause and that loop
cleanup code should merely be written after the loop with either
comments or vertical whitespace used for logical grouping, rather than
having the else clause available for that purpose.

The choice to be made is whether the potential for improvement in
understanding of the nature and purpose of the else clause amongst
Python programmers as a whole (even those that don't use static analysis
tools like pylint or pychecker) would be worth the mild aggravation to
folks like Steven and Gerald that currently use the else clause to
logically group cleanup code with the relevant loop.

(That said, I don't think the question should even be asked of
python-dev without a patch on the tracker that actually adds the new
warning. I personally have several other Python issues higher on my
to-do list that I have yet to find the roundtuits to address, so I'm not
likely to be producing such a patch anytime soon...)

Cheers,
Nick.

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



More information about the Python-ideas mailing list