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

Stefan Behnel stefan_ml at behnel.de
Sun Mar 3 13:15:54 CET 2013

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.


More information about the Python-ideas mailing list