Nick Coghlan <ncogh...@gmail.com> added the comment:

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

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue33146>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to