[Python-ideas] "try with" syntactic sugar

Bruce Frederiksen dangyogi at gmail.com
Fri Feb 27 02:28:29 CET 2009

Daniel Stutzbach wrote:
> Hi Bruce,
> I bow to your superior regular expression knowledge.  :)  However, 
> your version counts the number of "try"s that are followed by "with".  
> Mine counts the number of "with"s that are preceded by "try" (which I 
> think the more relevant metric?).  Any chance you could alter your script?

Sorry, my mistake.

How about this?

import re, sys

re_with = re.compile(r'''
  ^(?P<indent>\s*)                          # capture the indent
                                            # (might be try, might be with)
      (?:[ \t]*(?:\#.*)?[\r\n]+)?           # newlines (ignoring comments)
      (?P=indent)[ \t]+                     # kick out the indent level
   with\s (?:[^#:]*(?:(?:\#.*)?[\r\n]+)?)*: # with .*: (ignoring comments
                                            # and newlines before :)
''', re.MULTILINE | re.VERBOSE)            

try_with = 0
total = 0
for fname in sys.argv[1:]:
    data = open(fname).read()
    for match in re_with.finditer(data):
        if match.group('try'): try_with += 1
        total += 1
print 'try-with:', try_with, 'out of:', total, '(', 

On my code, I now get:

try-with: 1 out of: 47 ( 2.12765957447 %)

On my last response, I mentioned a suggestion to add __throw__ to 
context managers.  But then I remembered that the __exit__ method is 
already given the exception information if an exception is raised.  So 
you can already do what I was suggesting now.

I'm still curious as to how often you could share try/except cases by 
writing your own context managers.

-bruce frederiksen

More information about the Python-ideas mailing list