[Python-ideas] One-line "try with" statement

Terry Reedy tjreedy at udel.edu
Sun Mar 3 19:27:46 CET 2013

On 3/2/2013 5:45 PM, Alan Johnson wrote:
> It seems to me that one of the intended uses of the with statement
> was to automate simple initialization and deinitialization, which
> often accompanies a try block.  It wouldn't be a game changing thing
> by any means, but has anybody ever thought about allowing a "try
> with" statement on one line?  So instead of:
> try:
 >   with context_manager():
 >   … bunch of code …
 > except:
 >   … exception handler …
> you would have:
> try with context_manager():
 >    … bunch of code …
 > except:
 >   … exception handler …
> I envision the two examples being equivalent, the principle benefits
> being readability

To me it is less readable. And it only works when the with statement is 
the entire suite for the try: part.

> and one less indention level for the with block

There is no end of possible combinations of statements and others have 
been proposed with the same justification - saving an indent level -- 
and rejected. If indent level is really a problem, use fewer spaces per 
indent, or pull highly indented blocks into a separate function.

Terry Jan Reedy

More information about the Python-ideas mailing list