[Python-ideas] "try with" syntactic sugar

Georg Brandl g.brandl at gmx.net
Fri Feb 27 17:18:41 CET 2009


Christian Heimes schrieb:
> 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.

I'd assumed this is already implicit in the proposal.

> Additionally I'd like to have multiple arguments, too.

+1 to that (it should have been there in the beginning).

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

I still like it better with the "try" before the "with".

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.




More information about the Python-ideas mailing list