[Python-ideas] for/else statements considered harmful
Calvin Spealman
ironfroggy at gmail.com
Sat Jun 16 19:05:48 CEST 2012
On Wed, Jun 6, 2012 at 7:20 PM, 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?")
I read it not as for/else and while/else, but break/else and this has
been a much
more natural framing for myself and those I've used the framing to explain the
behavior to.
> 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.
>
> 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.
>
> I'll isolate the for/else/finally code from my fork and post a patch this
> week-end, hopefully.
>
> — Alice.
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
--
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://techblog.ironfroggy.com/
Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy
More information about the Python-ideas
mailing list