[New-bugs-announce] [issue15806] Add context manager for the "try: ... except: pass" pattern

Raymond Hettinger report at bugs.python.org
Wed Aug 29 07:15:15 CEST 2012


New submission from Raymond Hettinger:

It is a somewhat common pattern to write:

   try:
       do_something()
   except SomeException:
       pass

To search examples in the standard library (or any other code base) use:

    $ egrep -C2 "except( [A-Za-z]+)?:" *py  | grep -C2 "pass"

In the Python2.7 Lib directory alone, we find 213 examples.

I suggest a context manager be added that can ignore specifie exceptions.  Here's a possible implementation:

class Ignore:
    ''' Context manager to ignore particular exceptions'''

    def __init__(self, *ignored_exceptions):
        self.ignored_exceptions = ignored_exceptions

    def __enter__(self):
        return self

    def __exit__(self, exctype, excinst, exctb):
        return exctype in self.ignored_exceptions

The usage would be something like this:

    with Ignore(IndexError, KeyError):
        print(s[t])

Here's a real-world example taken from zipfile.py:

    def _check_zipfile(fp):
        try:
            if _EndRecData(fp):
                return True         # file has correct magic number                                                                        
        except IOError:
            pass
        return False

With Ignore() context manager, the code cleans-up nicely:

    def _check_zipfile(fp):
        with Ignore(IOError):
            return bool(EndRecData(fp))  # file has correct magic number                                                                        
        return False

I think this would make a nice addition to contextlib.

----------
assignee: ncoghlan
messages: 169337
nosy: ncoghlan, rhettinger
priority: low
severity: normal
status: open
title: Add context manager for the "try: ... except: pass" pattern
type: enhancement
versions: Python 3.4

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15806>
_______________________________________


More information about the New-bugs-announce mailing list