[Python-ideas] for/else syntax

Mike Meyer mwm-keyword-python.b4bdba at mired.org
Sat Oct 3 01:42:45 CEST 2009


On Fri, 2 Oct 2009 17:12:25 +0100
Michael Foord <fuzzyman at gmail.com> wrote:

> 2009/10/2 Arnaud Delobelle <arnodel at googlemail.com>
> > On 2 Oct 2009, at 15:43, Steven D'Aprano wrote:
> >> Perhaps there should be. Does anyone know why there isn't? It seems an
> >> arbitrary restriction to me, because the following pieces of code are
> >> not equivalent:
> >>
> >> # not currently legal
> >> try:
> >>   if cond:
> >>       raise ValueError
> >> else:
> >>   print "no exception was raised"
> >> finally:
> >>   print "done"
> >>
> >>
> >>  But the above is the same as:
> >
> > try:
> >    if cond:
> >       raise ValueError
> >    print "no exception was raised"
> > finally:
> >    print "done"
> >
> But as always with Python, the code in the else clause is not protected by
> the except so that you do not incorrectly handle unexpected exceptions.

Um, there's not an except clause to protect anything there. In both
cases, the code flows from the try: block to the else: block (even
without the else: line) and then the finally: block, with an exception
in the try: or else: block skipping the rest of both.  Consider the
three cases:

1) no exception raised - both cases print "no exception was raised" and "done".
2) exception in original try block - both cases just print "done".
3) exception in original else - both cases print whatever prints from
   the else block before the exception, and then "done".

So the else: might as well be a pass.

   <mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org



More information about the Python-ideas mailing list