[Python-ideas] for/else statements considered harmful

Arnaud Delobelle arnodel at gmail.com
Thu Jun 7 16:00:39 CEST 2012

On 7 June 2012 00:20, Alice Bevan–McGregor <alice at gothcandy.com> 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?")

My solution: don't talk about a for/else construct, but talk about a
for/break/else block instead. Then the semantics become obvious again.

> 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
> 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.

I think your use of finally is as unfortunate as the current use of
else:  usually, finally is *always* executed, irrespective of what
happened in the try block.  Your new use goes against that.



More information about the Python-ideas mailing list