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

Tomasz Rybak tomasz.rybak at post.pl
Sun Mar 3 11:32:16 CET 2013


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__.

Regards.

-- 
Tomasz Rybak  GPG/PGP key ID: 2AD5 9860
Fingerprint A481 824E 7DD3 9C0E C40A  488E C654 FB33 2AD5 9860
http://member.acm.org/~tomaszrybak

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130303/1bd928c7/attachment.pgp>


More information about the Python-ideas mailing list