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

Gerald Britton gerald.britton at gmail.com
Fri Oct 9 01:35:51 CEST 2009


Ach,  I just whipped it up in a hurry.  I didn't pull it from live
code (or even test it).   A better (working) version:

>>> x = []
>>> del i
>>> for i, j in x:
...   do_something()
... else:
...   i = vars().get('i',-1)
...
>>> i
-1
>>>

And before someone says _again_ that the else is not necessary here,
that's not the reason I use it.  I use it to structure the code so
that it is obvious that the stuff in the else clause belongs to the
for loop, not to code that follows it.

The point is, there are valid reasons to use this construct.  That's
just one of many, many more.  I would fight tooth-and-nail against a
warning message, if I thought there was even the faintest chance of it
being considered.  As it is, there is essentially no chance that it
will be considered for the compiler (pylint is another matter,  I
think that it _should_ be there).

On Thu, Oct 8, 2009 at 6:52 PM, Yuvgoog Greenle <ubershmekel at gmail.com> wrote:
> 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.
>
> --yuv
>



-- 
Gerald Britton



More information about the Python-ideas mailing list