for-else
Jared Grubb
jared.grubb at gmail.com
Thu Mar 6 02:47:31 EST 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
following:
for foo in bar_sequence:
# normal iteration
spam(foo)
if funky(foo):
break
except StopIteration, exc:
# the iterator stopped normally
eggs(exc)
except BreakException, exc:
# the iterator exited abnormally, i.e. 'break'
sausage()
Giving a loop a "try"-like behavior could open up the ability to jump out of
multiple levels of loops:
while 1:
while 1:
break
except BreakException:
break # or re-raise?
Or maybe you can do "raise BreakException(2)" without any except clauses at
all? Just my $0.02.
Jared
On 4 Mar 2008, at 12:27, bearophileHUGS at lycos.com wrote:
Raymond HettInger:
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
flags.
I'd like it to be renamed to something more natural :-)
Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080305/197060b0/attachment-0001.html>
More information about the Python-list
mailing list