[Python-ideas] for/else syntax

Steven D'Aprano steve at pearwood.info
Fri Oct 2 07:06:17 CEST 2009


On Thu, 1 Oct 2009 11:07:19 am Yuvgoog Greenle wrote:
> On python-dev the subject of for/else statements came up, so I had to
> mention how "ambiguous" the syntax seems to me. By "ambiguous" I
> meant that it's not obvious what should happen in the for/else and
> while/else constructs (the except/else construct is readable and
> great imo btw).
>
> Even though it's documented, for me it's a bad construct because it
> can and will always be misinterpreted by a non-trivial amount of
> people seeing it for the first time. It's unreadable and confusing
> because the "else" isn't referring to the "for" it's in reference to
> the "break". 

That's a very fine distinction you are drawing, and I don't think it is 
useful. The else block runs when you exit the for-loop normally, by 
falling off the end. There are three ways to exit the for-loop without 
falling off the end: break, raise and return. raise and return are 
special: return exits the function immediately, nothing further gets 
run, and uncaught exceptions do similar. So the only way to exit a 
for-loop abnormally and still keep processing is with break. Hence you 
argue that the else refers to the break. But of course you can't have a 
break outside of a for loop, so else is equally associated with for.


And in fact, it is legal to have for loops without a break but include 
an else. Is it useful? I don't know, but Python can't forbid them 
without breaking (pun not intended) code like this:

for x in xs:
    if __debug__:
        break
else:
    print "whatever"

"if __debug__: suite" is special: the Python compiler optimizes the 
entire suite away when running with the -O flag. So if Python would 
treat the presence of an else as an error unless there was a break, you 
could have some code which was, or wasn't, legal according to the 
presence of the optimize flag. This is clearly a Bad Thing.

Hence, even if for...else with no breaks are useless, they must be 
allowed.


> To make things worse, it's not that newcomers will say "hmm, what
> does this for/else thing do? lets look at the manual", they will
> mistakenly assume they understand what the construct means. For
> evidence, see the for/else construct in the django templating
> language where "else" means the loop didn't run. 

That's not evidence of what newcomers will do. It's evidence that other 
languages can do things differently from Python.



-- 
Steven D'Aprano



More information about the Python-ideas mailing list