[Python-ideas] for/else statements considered harmful

Steven D'Aprano steve at pearwood.info
Thu Jun 7 01:45:36 CEST 2012

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.  When used in an if/else block the 
> conditional code is executed if the conditional passes, and the else 
> block is executed if the conditional fails.  Compared to for loops where 
> the for code is repeated and the else code executed if we "naturally 
> fall off the loop".  (The new user's reaction was "why the hoek would I 
> ever use for/else?")

Yes, I love for/else and while/else but regret the name. The else is 
conceptually unlike the else in if/else, and leads to the common confusion 
that the else suite if the iterable is empty.

> I forked Python 3.3 to experiment with an alternate implementation that 
> follows the logic of pass/fail implied by if/else: (and to refactor the 
> stdlib, but that's a different issue ;)
>    for x in range(20):
>        if x > 10: break
>    else:
>        pass # we had no values to iterate
>    finally:
>        pass # we naturally fell off the loop

+10000 :)

> It abuses finally (to avoid tying up a potentially common word as a 
> reserved word like "done") but makes possible an important distinction 
> without having to perform potentially expensive length calculations 
> (which may not even be possible!) on the value being iterated: that is, 
> handling the case where there were no values in the collection or 
> returned by the generator.
> Templating engines generally implement this type of structure.  Of 
> course this type of breaking change in semantics puts this idea firmly 
> into Python 4 land.

Sadly, yes. Where were you when Python 3.0 was still being planned? :)

> I'll isolate the for/else/finally code from my fork and post a patch 
> this week-end, hopefully.
>     — Alice.

Many thanks.


More information about the Python-ideas mailing list