[Python-ideas] for/else syntax

Steven D'Aprano steve at pearwood.info
Sat Oct 3 09:30:42 CEST 2009


On Sat, 3 Oct 2009 01:34:34 am Nick Coghlan wrote:

> 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).

It's quite surprising to me that the following two pieces of code are 
equivalent:

try:
    print "Catch exceptions here"
except AttributeError:  # Keep the compiler happy,
    raise               # avoid SyntaxError.
else:
    print "Don't catch exceptions here."
finally:
    print "Done"

and:


try:
    print "Catch exceptions here"
    print "Don't catch exceptions here."
finally:
    print "Done"


I've spent some time playing around with various cases, and I can't find 
any example where they behaviour differently, but I am still not 
convinced that there's not some unusual corner case where they differ.




-- 
Steven D'Aprano



More information about the Python-ideas mailing list