[Python-ideas] for/else statements considered harmful
Alice Bevan–McGregor
alice at gothcandy.com
Thu Jun 7 01:20:07 CEST 2012
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 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.
More information about the Python-ideas
mailing list