This is a backport of the
ExceptionGroup classes from Python 3.11.
It contains the following:
- A utility function (
exceptiongroup.catch()) for catching exceptions possibly nested in an exception group
- Patches to the
TracebackExceptionclass that properly formats exception groups (installed on import)
- An exception hook that handles formatting of exception groups through
TracebackException(installed on import)
The only difference with the Python 3.11 standard library implementation is that there is no
__note__ attribute in
If this package is imported on Python 3.11 or later, the built-in implementations of the exception group classes are used instead,
TracebackException is not monkey patched and the exception hook won't be installed.
.. seealso:: https://docs.python.org/3/library/exceptions.html
Due to the lack of the
except* syntax introduced by PEP 654 in earlier Python versions, you need to use
exceptiongroup.catch() to catch exceptions that are potentially nested inside an exception group. This function returns a context manager that calls the given handler for any exceptions matching the first argument.
So, the following Python 3.11+ code:
try: ... except* (ValueError, KeyError) as exc: print('Caught exception:', type(exc))
would be written as follows:
from exceptiongroup import catch def handler(exc: Exception) -> None: print('Caught exception:', type(exc)) with catch((ValueError, KeyError), handler): ...
Just like with
except*, you cannot handle