for / while else doesn't make sense

Erik python at lucidity.plus.com
Sat May 21 03:20:02 EDT 2016


On 20/05/16 01:06, Steven D'Aprano wrote:

> In my experience, some people (including me) misunderstand "for...else" to
> mean that the else block runs if the for block *doesn't*. It took me the
> longest time to understand why this didn't work as I expected:
>
> for x in seq:
>      pass
> else:
>      print("seq is empty")

So why don't we consider if that should be a syntax error - "else" 
clause on "for" loop with no "break" in its body? I know that doesn't 
change your fundamental mental model, but it's a hint that it's wrong :)

As it's backwards-incompatible, it could be introduced using a 
__future__ import (a precedent is 'generators' and the "yield" keyword 
back in the day) which those who would like the new check could add to 
the top of their sources.

But also, as you say, any instances of that construct in the wild is 
almost certainly a bug, so it would be good to be able to test code 
using a command-line or similar switch to turn on the behaviour by 
default for testing existing bodies of code.

I notice that pylint complains about this (as a warning). Is there any 
reason why this should _not_ just be considered an error and be done 
with it?

E.



More information about the Python-list mailing list