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.

Title: Add contextlib.convert_exception manager
Type: enhancement Stage:
Components: Library (Lib) Versions: Python 3.7
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: ncoghlan, steven.daprano
Priority: normal Keywords:

Created on 2017-06-28 15:48 by steven.daprano, last changed 2022-04-11 14:58 by admin.

Messages (2)
msg297193 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2017-06-28 15:48
As discussed on Python-Ideas, there's some interest in a context manager that can convert an exception from one type to another (similarly to the way PEP 479 has StopIteration converted to RuntimeError.

See the thread starting here:

and particularly Nick's comment here:

I've written a recipe on ActiveState:

which acts as both a context manager and function decorator. That can be used as proof-of-concept or as a basis for a PR.
msg297245 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2017-06-29 02:43
Also clarifying a point that came up later in the thread [1]: one of the motivating examples that came up in the thread was the idea of using this to catch AttributeError exceptions in property and __getattr__ implementations and convert them to RuntimeError.

I don't actually think that's a good use case: using a static analysis tool like 'pylint -E' or mypy, or the builtin error checking in an advanced IDE like PyCharm is a much better approach to detecting that kind of problem.

Instead, the valid use cases I see for runtime exception conversion are in:

- framework development, where you're invoking arbitrary code that you didn't write and want to ensure it can't falsely trigger an exception based event reporting protocol (this is the PEP 479 use case, and we may end up doing this for the exec_module() hook in the import system as well)

- adapting between two different exception based event reporting protocols (e.g. KeyError <-> AttributeError, StopIteration -> AsyncStopIteration)

Date User Action Args
2022-04-11 14:58:48adminsetgithub: 74975
2017-06-29 02:43:10ncoghlansetmessages: + msg297245
2017-06-28 15:48:31steven.dapranocreate