This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author rhettinger
Recipients ncoghlan, rhettinger
Date 2012-08-29.05:15:14
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
It is a somewhat common pattern to write:

   except SomeException:

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):

Here's a real-world example taken from

    def _check_zipfile(fp):
            if _EndRecData(fp):
                return True         # file has correct magic number                                                                        
        except IOError:
        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.
Date User Action Args
2012-08-29 05:15:15rhettingersetrecipients: + rhettinger, ncoghlan
2012-08-29 05:15:15rhettingersetmessageid: <>
2012-08-29 05:15:14rhettingerlinkissue15806 messages
2012-08-29 05:15:14rhettingercreate