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.

classification
Title: Add context manager for the "try: ... except: pass" pattern
Type: enhancement Stage:
Components: Versions: Python 3.4
process
Status: closed Resolution: fixed
Dependencies: Superseder: Rename contextlib.ignore to contextlib.suppress
View: 19266
Assigned To: ncoghlan Nosy List: alex, barry, chris.jerdonek, cvrebert, eric.smith, ezio.melotti, giampaolo.rodola, jcea, loewis, ncoghlan, pitrou, python-dev, rhettinger, zaytsev
Priority: low Keywords:

Created on 2012-08-29 05:15 by rhettinger, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (15)
msg169337 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2012-08-29 05:15
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.
msg169340 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2012-08-29 05:35
Hmm, the __exit__ method was doing exact matches by exception type, so KeyError wouldn't match LookupError or Exception.

There are probably a number of ways to fix this, but it may be easiest to use the builtin exception catching mechanisms:

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):
        if exctype is not None:
            try:
                raise
            except self.ignored_exceptions:
                return True
msg169341 - (view) Author: Alex Gaynor (alex) * (Python committer) Date: 2012-08-29 05:55
Why not just: issubclass(exctype, self.exception_types)?
msg169342 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2012-08-29 06:06
Yes, something along those lines would be *much* better:

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 and issubclass(exctype, self.ignored_exceptions)
msg169343 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2012-08-29 06:20
I'd just write it with @contextmanager. Making it easier to cleanly factor out exception handling is one of the main reasons that exists.

  @contextmanager
  def ignored(*exceptions):
    """Context manager to ignore particular exceptions"""
    try:
        yield
    except exceptions:
        pass

While the class based version would likely be fractionally faster, the generator based version is more obviously correct.
msg169346 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2012-08-29 07:28
I think I'm -1 on this.

This saves two lines, but makes the code less explicit, it can't be used for try/except/else or try/except/except, it requires an extra import, the implementation is simple enough that it doesn't necessary need to be in the stdlib, it might encourage bad style, and it's slower.

Some of these downsides are indeed somewhat weak, but the upside of saving two lines is quite weak too IMHO.
msg169348 - (view) Author: Martin v. Löwis (loewis) * (Python committer) Date: 2012-08-29 07:51
I think the zipfile example is really a bad example. IMO, it would
best be written as

try:
  return bool(EndRecData(fp))
except IOError:
  return False

i.e. there shouldn't be a pass statement at all in this code, and the if can be dropped whether you use try-except or with.
msg169357 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2012-08-29 09:55
(Note: I'm not yet convinced this is a good idea. I'm definitely considering it, though)

As with many context managers, a key benefit here is in the priming effect for readers. In this code:

    try:
       # Whatever
    except (A, B, C):
       pass

the reader doesn't know that (A, B, C) exceptions will be ignored until the end. The with statement form makes it clear before you start reading the code that certain exceptions won't propagate:

    with ignored(A, B, C):
        # Whatever

I'm not worried that it makes things less explicit - it's pretty obvious what a context manager called "ignored" that accepts an arbitrary number of exceptions is going to do.

One other thing it does is interact well with ExitStack - you can stick this in the stack of exit callbacks to suppress exceptions that you don't want to propagate.
msg169358 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2012-08-29 10:06
> As with many context managers, a key benefit here is 
> in the priming effect for readers.

The "focus" is mostly on what it's being executed rather than what it's being ignored though.

"Do this operation and ignore these exceptions if they occur"
vs.
"Ignore these exceptions if they occur while doing this operation."

> I'm not worried that it makes things less explicit - it's pretty
> obvious what a context manager called "ignored" that accepts an
> arbitrary number of exceptions is going to do.

It's still understandable, but while I'm familiar with the semantics of try/except, I wouldn't be sure if e.g. this just ignored those specific exceptions or even their subclasses without checking the doc/code.

> One other thing it does is interact well with ExitStack - you can
> stick this in the stack of exit callbacks to suppress exceptions that
> you don't want to propagate.

This seems a good use case.
msg169363 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2012-08-29 10:51
If this is desirable then I think it would be better as a classmethod of Exception:

with KeyError.trap():
    do_something()
msg169364 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2012-08-29 11:08
While the classmethod version has some appeal, it doesn't extend well to handling multiple exception types.

I'm -0 on this, in any event. I think the original code is more clear. Why force people to learn (or recognize) a second idiom for something so simple?
msg183934 - (view) Author: Roundup Robot (python-dev) (Python triager) Date: 2013-03-11 05:27
New changeset 406b47c64480 by Raymond Hettinger in branch 'default':
Issue #15806: Add contextlib.ignored().
http://hg.python.org/cpython/rev/406b47c64480
msg183942 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2013-03-11 08:02
FTR, Raymond and I discussed this on IRC and I gave it a +1 before he committed it.

The advantage the callable form has over a class method is that it readily scales to ignoring multiple exception types in a single with statement.
msg195879 - (view) Author: Yury V. Zaytsev (zaytsev) Date: 2013-08-22 11:54
Hi Raymond,

This is a brilliant idea, but before it hits the streets, couldn't you possibly consider extending it with a kwarg to control the depth of the exception stack?

The use case I have for that are snippets like this:

    with ignored(ValueError, TypeError), ignored(ValueError, TypeError), ignored(ValueError, TypeError):
        a()
        b()
        c()

Or else I could write this as

    with ignored(ValueError, TypeError):
        a()

    with ignored(ValueError, TypeError):
        b()

    with ignored(ValueError, TypeError):
        c()

... but either way it looks bad. This looks a bit better to me:

    with ignored(ValueError, TypeError, depth=3):
        a()
        b()
        c()

If you deem this to be unacceptably unpythonic, then please ignore my suggestion.
msg195890 - (view) Author: Yury V. Zaytsev (zaytsev) Date: 2013-08-22 13:44
Actually, please disregard my idea. It's way to dangerous, especially in the case of multiple exceptions to ignore :-(
History
Date User Action Args
2022-04-11 14:57:35adminsetgithub: 60010
2013-10-16 22:31:55belopolskysetsuperseder: Rename contextlib.ignore to contextlib.suppress
2013-10-16 22:31:31belopolskylinkissue19266 dependencies
2013-10-11 16:51:53giampaolo.rodolasetnosy: + giampaolo.rodola
2013-08-22 13:44:51zaytsevsetmessages: + msg195890
2013-08-22 11:54:09zaytsevsetnosy: + zaytsev
messages: + msg195879
2013-03-16 00:44:20barrysetnosy: + barry
2013-03-11 08:02:21ncoghlansetmessages: + msg183942
2013-03-11 05:28:04rhettingersetstatus: open -> closed
resolution: fixed
2013-03-11 05:27:06python-devsetnosy: + python-dev
messages: + msg183934
2012-08-29 11:38:25jceasetnosy: + jcea
2012-08-29 11:08:31eric.smithsetnosy: + eric.smith
messages: + msg169364
2012-08-29 10:51:09pitrousetnosy: + pitrou
messages: + msg169363
2012-08-29 10:06:59ezio.melottisetmessages: + msg169358
2012-08-29 09:55:28ncoghlansetmessages: + msg169357
2012-08-29 08:01:43cvrebertsetnosy: + cvrebert
2012-08-29 07:51:30loewissetnosy: + loewis
messages: + msg169348
2012-08-29 07:28:42ezio.melottisetnosy: + ezio.melotti
messages: + msg169346
2012-08-29 06:43:47chris.jerdoneksetnosy: + chris.jerdonek
2012-08-29 06:20:48ncoghlansetmessages: + msg169343
2012-08-29 06:06:15rhettingersetmessages: + msg169342
2012-08-29 05:55:37alexsetmessages: + msg169341
2012-08-29 05:35:27rhettingersetmessages: + msg169340
2012-08-29 05:17:50alexsetnosy: + alex
2012-08-29 05:15:14rhettingercreate