[Python-ideas] "try with" syntactic sugar

Daniel Stutzbach daniel at stutzbachenterprises.com
Thu Feb 26 15:36:29 CET 2009


Around two-thirds of the time, whenever I use the wonderful new "with"
construct, it's enclosed in a "try-except" block, like this:

try:
   with something as f:
        many lines of code
except some_error:
    handle error

The "with" statement is great, but it results in the bulk of the code being
indented twice.  I'd like to propose a little syntactic sugar, the "try
with":

try with something as f:
    many lines of code
except some_error:
    handle error

It saves one line of vertical space, and gets rid of an indentation level
for the bulk of the code that rests within the "with" statement.  Thoughts?

Here's a short script to count how many uses of "with" within your code are
immediately preceded by "try":

#!/usr/bin/python
import re, sys

re_with = re.compile(r'(try:[ \t]*)?[\r\n]+[ \t]+with ')

try_with = 0
total = 0
for fname in sys.argv[1:]:
    data = open(fname).read()
    for match in re_with.findall(data):
        if match: try_with += 1
        total += 1

print 'try-with:', try_with, 'out of:', total, '(',
try_with*100.0/total,'%)'


Usage:
Cashew:~$ /tmp/count_try_with.py *.py
try-with: 17 out of: 25 ( 68.0 %)

--
Daniel Stutzbach, Ph.D.
President, Stutzbach Enterprises, LLC <http://stutzbachenterprises.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20090226/e7ce12a1/attachment.html>


More information about the Python-ideas mailing list