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 ncoghlan
Recipients jaraco, ncoghlan, rhettinger, serhiy.storchaka
Date 2018-03-27.13:11:29
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1522156289.15.0.467229070634.issue33146@psf.upfronthosting.co.za>
In-reply-to
Content
I wouldn't expand the scope of contextlib.suppress, since it has a pretty clear purpose: pretend the exception never happened. (This was even clearer with the original "ignored" name, before I was talked into changing it to use the current more technically correct, but far less intuitive, name - a decision I still regret).

However, when writing tests, or otherwise introspecting thrown exceptions (i.e. in programs about programs), it's not uncommon for me to want a construct like:

    with catch(FileNotFoundError) as err:
        os.remove(somefile)

    if err.caught is not None:
        ...

The benefit over the try/catch form is similar to the benefits of suppress:

1. Up front declaration that that kind of exception isn't going to escape and execution will continue after the suite
2. More efficient use of vertical whitespace (one extra line instead of three)

In this case, we could also end up expanding the API to provide a better building block for testing tools like "assertRaises" and "assertRaisesRegex" by accepting a "filter" callback argument that receives the caught exception, and can either return False to suppress it, True to reraise it, or explicitly raise a different exception to replace it. (That suggested callback API is deliberately similar to an __exit__ implementation that only accepts the exception value, rather than the full type/value/traceback triple).

(The simpler name may mean that folks end up preferring catch() to suppress() even when they don't need the result of __enter__. I'd be OK with that outcome).
History
Date User Action Args
2018-03-27 13:11:29ncoghlansetrecipients: + ncoghlan, rhettinger, jaraco, serhiy.storchaka
2018-03-27 13:11:29ncoghlansetmessageid: <1522156289.15.0.467229070634.issue33146@psf.upfronthosting.co.za>
2018-03-27 13:11:29ncoghlanlinkissue33146 messages
2018-03-27 13:11:29ncoghlancreate