[Python-Dev] PEP 340: Else clause for block statements
Shane Hathaway
shane at hathawaymix.org
Mon May 2 15:46:31 CEST 2005
Anders J. Munch wrote:
> in opening('file1') as f1:
> ...
> in opening('file2') as f2:
> ...
> except IOError:
> print "file1 not available, I'll try again later"
>
> I rather like this version, because it is patently clear what should
> happen if there is no except-clause: The exception propagates
> normally.
My eyes would expect the exception handler to also catch IOErrors
generated inside the block statement body. My eyes would be deceiving
me, of course, but Python isn't currently so subtle and it probably
shouldn't be.
You could also do this with a suitable iterator.
def opening_or_skipping(fn):
try:
f = open(fn)
except IOError:
print "file1 not available, I'll try again later"
else:
try:
yield f
finally:
f.close()
Shane
More information about the Python-Dev
mailing list