[Python-ideas] Nudging beginners towards a more accurate mental model for loop else clauses

Steven D'Aprano steve at pearwood.info
Fri Jun 8 17:06:23 CEST 2012


Nick Coghlan wrote:

>   for x in iterable:
>     ...
>   except break:  # Implicit in the semantics of loops
>     pass
>   else:
>     ...
> 
> Would it be worth adding the "except break:" clause to the language
> just to make it crystal clear what is actually going on? I don't think
> so, but it's still a handy way to explain the semantics while gently

I agree that it is *not* worthwhile. The main reason is that "except break" 
would add a new and different form of confusion (or at least complication): 
what happens when you return or raise from inside the loop rather than break?

If "except break" *only* executes after a break (like it says!) that opens the 
door to "except return" and "except raise". Bleh. I really don't think we need 
this level of complication in loops.

But if "except break" runs on *any* early exit from the loop (break, return or 
raise), then the name is misleading and confusing and we now have a new and 
exciting education problem to replace the old one. (Albeit probably a simpler 
problem.)


> steering people away from linking for/else and if/else too closely. I
> actually agree all of the else clauses really *are* quite closely
> related (hence the consistent use of the same keyword), but the

I'm not so sure that they are that close, except in the trivial sense of 
having two alternatives, "A happens, otherwise B happens". In the case of 
for/else, the A is implied (a break, return or raise), which makes it rather 
different from if/else where both alternatives are explicit.

Despite the similarity with try/else, I think it is quite a stretch to link 
the semantics of for/else with the word "else". It simply is not a good choice 
of keyword. If it were, we wouldn't be having this discussion.

Although it would have cost an additional keyword, I think that for/else and 
while/else should have been written as for/then and while/then, since that 
accurately describes what they do (unless you're Dutch *wink*).

for x in seq:
    ...
then:
    ...


There would be no implication that the "then" clause is executed *instead of* 
the loop part, instead the natural implication is that it is executed *after* 
the loop.

(And then we could have introduced an "else" clause to do what people expect 
the else clause to do, namely run if the loop doesn't run.)




-- 
Steven




More information about the Python-ideas mailing list