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

Steven D'Aprano steve at pearwood.info
Fri Oct 9 04:44:43 CEST 2009


On Fri, 9 Oct 2009 03:17:38 am Stephen J. Turnbull wrote:
> I think I would probably be saved at least once
> in my remaining years of Python programming by Nick's proposal, too.

That makes no sense. If there's no difference between:

for x in seq:
    pass
else:
    whatever()

and 

for x in seq:
    pass
whatever()

then what could the warning save you from? Embarrassment when people 
laugh at your coding style?


Perhaps you're thinking of the following:

for x in seq:
    if flag:
        whatever()
else:  # oops, I wanted this to be inside the loop
    something()


But Nick's warning is insufficient, because it is defeated by the 
presence of a break *anywhere* in the loop:

for x in seq:
    if today == tuesday: break
    if flag:
        whatever()
else:  # oops, I wanted this to be inside the loop
    something()


The fact that it, occasionally, will catch a completely unrelated error 
(you outdented the else clause in if...else) is a fluke.



-- 
Steven D'Aprano



More information about the Python-ideas mailing list