[Python-ideas] "try with" syntactic sugar

Calvin Spealman ironfroggy at gmail.com
Thu Feb 26 15:44:00 CET 2009


+0

But... Do we also add try for:, try if:, try while:, etc.? Not
terrible, but potentially terrible.

On Thu, Feb 26, 2009 at 9:36 AM, Daniel Stutzbach
<daniel at stutzbachenterprises.com> wrote:
> 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
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
>



-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://techblog.ironfroggy.com/
Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy



More information about the Python-ideas mailing list