On Wed, Jun 28, 2017 at 12:25 PM, Nick Coghlan email@example.com wrote:
While generator functions now do that implicitly for StopIteration, and "raise X from Y" lets people write suitable exception handlers themselves, we don't offer an easy way to do it with a context manager (with statement as stack boundary), asynchronous context manager (async with statement as stack boundary), or a function decorator (execution frame as stack boundary).
So while I prefer "contextlib.convert_exception" as the name (rather than the "exception_guard" Steven used in his recipe), I'd definitely be open to a bugs.python.org RFE and a PR against contextlib to add such a construct to Python 3.7.
We'd have a few specific API details to work out (e.g. whether or not to accept arbitrary conversion functions as conversion targets in addition to accepting exception types and iterables of exception types, whether or not to allow "None" as the conversion target to get the same behaviour as "contextlib.suppress"), but I'm already sold on the general concept.
I agree broadly, but I'm sure there'll be the usual ton of bikeshedding about the details. The idea behind this decorator, AIUI, is a declaration that "a FooException coming out of here is a bug", and if I were looking for that, I'd look for something about the function leaking an exception, or preventing exceptions. So maybe convert_exception will work, but definitely have a docs reference from contextlib.suppress to this ("if exceptions of this type would indicate code bugs, consider convert_exception instead"). In my testing, I've called it "no_leak" or some variant thereon, though that's a shorthand that wouldn't suit the stdlib.