Around two-thirds of the time, whenever I use the wonderful new "with" construct, it's enclosed in a "try-except" block, like this:<br><br>try:<br> with something as f:<br> many lines of code<br>
except some_error:<br> handle error<br><br>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":<br>
<br>try with something as f:<br> many lines of code<br>
except some_error:<br>
handle error<br>
<br>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?<br><br>Here's a short script to count how many uses of "with" within your code are immediately preceded by "try":<br>
<br>#!/usr/bin/python<br>import re, sys<br><br>re_with = re.compile(r'(try:[ \t]*)?[\r\n]+[ \t]+with ')<br><br>try_with = 0<br>total = 0<br>for fname in sys.argv[1:]:<br> data = open(fname).read()<br> for match in re_with.findall(data):<br>
if match: try_with += 1<br> total += 1<br><br>print 'try-with:', try_with, 'out of:', total, '(', try_with*100.0/total,'%)'<br><br><br>Usage:<br>Cashew:~$ /tmp/count_try_with.py *.py<br>
try-with: 17 out of: 25 ( 68.0 %)<br><blockquote style="margin: 1.5em 0pt;">--<br>
Daniel Stutzbach, Ph.D.<br>
President, <a href="http://stutzbachenterprises.com">Stutzbach Enterprises, LLC</a>
</blockquote>