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

Yuvgoog Greenle ubershmekel at gmail.com
Fri Oct 9 00:52:55 CEST 2009

Gerald, if this warning would have been generated you might have saved
yourself the mistakes on the previous thread.

Gerald wrote as an example of "for..else" being useful without a break:
> for i, j in enumerate(something):
>  # suite
>  i += 1
> else:
>  i = 0
> # i == number of things processed

If "# suite" has no break, "i" will always be 0. Either way after the
loop "i" isn't going to have the number of things processed (unless
"something" was empty). After being corrected Gerald wrote the
following remedied example:

> for i, j in enumerate(something):
>  # do something
>  i += 1
> else:
>  i = -1
> if i > 0:
>  # we did something

The last block "# we did something" is unreachable if "#do something"
has no break.

This isn't meant to go against Gerald here btw. I'm simply saying that
if even the best Pythonistas can cause havoc with "for...else" then
think about the noobs. Personally I would suggest not using the
"for...break...else" idiom at all but the least we can do is give a
warning when "for..else" is so obviously misused.

You could allow "break" outside of loops and simply ignore it, but you
don't allow it because it helps avoid bugs. Really, a warning is the
LEAST python can do here.


More information about the Python-ideas mailing list