jared.grubb at gmail.com
Thu Mar 6 08:47:31 CET 2008
I think bearophile makes an excellent point. I also have a hard time
remembering what else does.
I have always pictured that the "normal" behavior of a for loop is to get
through all the items. In special circumstances, it is necessary to break
out early. Therefore, it FEELS like the else loop should excute in the
"unexpected" or abnormal case (break), whereas the else actually gets
executed only when the entire loop DOES complete.
Ben Finney's idea of using an except clause after the for loop is an
excellent idea, as it makes it VERY clear when the case gets executed. (I
would disagree with his suggestion to use "else" in the break case, however,
because that would confuse the previous meaning.) However, you could then
make "break" equivalent to "raise BreakException", and provide the
for foo in bar_sequence:
# normal iteration
except StopIteration, exc:
# the iterator stopped normally
except BreakException, exc:
# the iterator exited abnormally, i.e. 'break'
Giving a loop a "try"-like behavior could open up the ability to jump out of
multiple levels of loops:
break # or re-raise?
Or maybe you can do "raise BreakException(2)" without any except clauses at
all? Just my $0.02.
On 4 Mar 2008, at 12:27, bearophileHUGS at lycos.com wrote:
FWIW, I'm very happy with for-else. Most of the time, you don't need
it, but when you do, it beats the heck out of doing silly tricks with
I'd like it to be renamed to something more natural :-)
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list