[Python-ideas] "try with" syntactic sugar
Christian Heimes
lists at cheimes.de
Fri Feb 27 12:18:58 CET 2009
Daniel Stutzbach wrote
> try with something as f:
> many lines of code
> except some_error:
> handle error
>
> It saves one line of vertical space, and gets rid of an indentation level
> for the bulk of the code that rests within the "with" statement. Thoughts?
Your proposal sounds like a very good idea. +1 from me.
I like to push your proposal even further and add the full set of exept,
else, finally blocks to the with statement. Additionally I'd like to
have multiple arguments, too.
Example
-------
log.info("Starting copy")
with somelock, open(infile, 'r') as fin, open(outfile, 'w') as fout:
fout.write(fin.read())
except Excption:
log.exception("An error has occured")
else:
log.info("Copy successful")
finally:
log.info("All done")
Equivalent
----------
log.info("Starting copy")
try:
with somelock:
with open(infile, 'r') as fin:
with open(outfile, 'w') as fout:
fout.write(fin.read())
except Excption:
log.exception("An error has occured")
else:
log.info("Copy successful")
finally:
log.info("All done")
Christian
More information about the Python-ideas
mailing list