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

Andrew Barnert abarnert at yahoo.com
Sun Mar 3 14:24:06 CET 2013

On Mar 3, 2013, at 4:15, Stefan Behnel <stefan_ml at behnel.de> wrote:

> Tomasz Rybak, 03.03.2013 11:32:
>> Dnia 2013-03-02, sob o godzinie 17:45 -0500, Alan Johnson pisze:
>>> 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 and one less indention level for the with block code.  So a similar justification to "lower < x < upper" idiom.  With standard 4 space indentation, existing with statements at the top of try blocks wouldn't even be any closer to the right margin.
>>> I'm no expert in Python interpreters, but it seems like a simple one-step internal conversion whenever this proposed syntax is encountered.  But obviously, it would involve that change to every interpreter in existence with no actual new functionality, so I'm sensitive to that.  Anyway, just a thought.
>> Isn't context manager supposed to deal with exceptions by itself?
>> If I understand things correctly with context manager you
>> do not need try/except - context manager will deal with
>> exceptions in __exit__.
> Yes, that's the main idea. The above example therefore strikes me as
> useless. If you need a try-except around a with block, then your context
> manager is doing something wrong.

A try-finally, sure, but a try-except is perfectly reasonable, idiomatic, and common. 

For example, if you do "with open(path) as f:" the context manager doesn't (and shouldn't) do anything to protect you from a FileNotFoundError in the open, or an IOError reading inside the block. If you want to, say, log, or try a backup file, how else would you handle that but a with inside a try?

That being said, I'm not sure this is necessary. For something you do repeatedly, you can always write a wrapper function. For something you only do once, I'm not sure the extra indent is that terrible.

More information about the Python-ideas mailing list