[Python-ideas] for/else statements considered harmful

Terry Reedy tjreedy at udel.edu
Thu Jun 7 06:31:30 CEST 2012

On 6/6/2012 7:20 PM, Alice Bevan–McGregor wrote:
> Howdy!
> Was teaching a new user to Python the ropes a short while ago and ran
> into an interesting headspace problem: the for/else syntax fails the
> obviousness and consistency tests.

I disagree. The else clause is executed when the condition (explicit in 
while loops, implicit in for loops) is false. Consider the following 
implementation of while loops in a lower-level pseudo-python:

label startloop
if condition:
   goto startloop

This is *exactly* equivalent to

while condition:

In fact, the absolute goto is how while is implemented in assembler 
languages, include CPython bytecode. If one converts a for-loop to a 
while-loop, you will see the same thing.

CPython bytecode for for-loops is a little more condensed, with a higher 
level FOR_ITER code. It tries to get the next item if there is one and 
catches the exception and jumps if not. (It also handles and hides the 
fact that there are two iterator protocols.) But still, an absolute 
'goto startloop' jump back up to FOR_ITER is added to the end of the 'if 
next' suite, just as with while-loops.

Terry Jan Reedy

More information about the Python-ideas mailing list