[Python-ideas] for/else syntax

Nick Coghlan ncoghlan at gmail.com
Fri Oct 2 17:34:34 CEST 2009


Steven D'Aprano wrote:
> On Fri, 2 Oct 2009 09:06:11 pm Nick Coghlan wrote:
> 
>> Just as there is no "try/else", 
> 
> 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"

Just drop the else line and you get the semantics you're after:

try:
    if cond:
        raise ValueError
    print "no exception was raised"
finally:
    print "done"

The reason except/else is necessary is that the code in the else clause
runs:

  1. Outside the scope of the exception handler
  2. Only if the except clause isn't taken

If there is no except clause, then the code that would have been in the
else clause can just be moved to the end of the try block (as in the
example above).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list