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

Alan Johnson alan at breakrs.com
Sat Mar 2 23:45:17 CET 2013

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:

		with context_manager():
			… bunch of code …
		… exception handler …

you would have:

	try with context_manager():
		… bunch of code …
		… 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.

Alan Johnson
Cofounder | Breakrs.com
347-630-2036 | alan at breakrs.com

More information about the Python-ideas mailing list