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

Steven D'Aprano steve at pearwood.info
Sat Jun 9 04:31:27 CEST 2012


Terry Reedy wrote:

On 6/8/2012 6:34 PM, Yuval Greenfield wrote:

> Loop statements may have an else clause; it is executed immediately after the loop but is skipped if the loop was terminated by a break statement. As I said in my reply on pydev, that is misleading.

Why is it misleading? It is incomplete insofar as it assumes the reader understands that (in the absence of try...finally) a return or raise will immediately exit the current function regardless of where in the function that return/raise happens to be. I think that's a fair assumption to make.

Other than that, Yuval's description seems both correct and simple to me. It precisely matches the semantics of for/else and while/else without introducing any additional complexity. The only thing it doesn't do is rationalise why the keyword is called "else" instead of a less confusing name.

The else clause executes if and when the loop condition is false. Period. Simple rule.

What is "the loop condition" in a for-loop? If you mean "when the iterable is false (empty)", that's simply incorrect, and is precisely the common error that many people make.

If on the other hand you are talking about the reader mentally converting a for-loop to an imaginary while-loop in their head, I hardly call that "simple". It wouldn't be simple even if for/else loops actually were implemented internally as a while loop.

If you mean something else, I have no idea what that could possibly be.

It will not execute if the loop is exited by break OR if the loop is exited by return OR if the loop is exited by raise OR if the loop never exits. (OR is the loop is aborted by external factors.) As far as else is concerned, there is nothing special about break exits compared to return or raise exits.

Right. Do we really need to explicitly document all of that under for/else? Surely we are allowed to assume a certain basic level of understanding of Python semantics -- not every page of the docs has to cover the fundamentals.

This kind of reminds me of the scene in "Red Dwarf" where Holly the computer is explaining to Lister that he is the last surviving crew member of the skip and that everyone else is dead. Paraphrasing:

 Holly: They're all dead. Everybody's dead, Dave.
 Lister: Peterson isn't, is he?
 Holly: Everybody's dead, Dave!
 Lister: Not Chen!
 Holly: Yes, Chen. Everyone. Everybody's dead, Dave!
 Lister: Rimmer?
 Holly: He's dead, Dave. Everybody is dead. Everybody is dead, Dave.
 Lister: Wait. Are you trying to tell me everybody's dead?

Yes Dave, a return will exit a for-loop without executing the code that follows.

wink

-- Steven



More information about the Python-ideas mailing list