Skip to main content

Backport of PEP 654 (exception groups)

Project description

Build Status Code Coverage

This is a backport of the BaseExceptionGroup and ExceptionGroup classes from Python 3.11.

It contains the following:

  • The exceptiongroup.BaseExceptionGroup and exceptiongroup.ExceptionGroup classes

  • A utility function (exceptiongroup.catch()) for catching exceptions possibly nested in an exception group

  • Patches to the TracebackException class that properly formats exception groups (installed on import)

  • An exception hook that handles formatting of exception groups through TracebackException (installed on import)

  • Special versions of some of the functions from the traceback module, modified to correctly handle exception groups even when monkey patching is disabled, or blocked by another custom exception hook:

    • traceback.format_exception()

    • traceback.format_exception_only()

    • traceback.print_exception()

    • traceback.print_exc()

  • A backported version of contextlib.suppress() from Python 3.12.1 which also handles suppressing exceptions inside exception groups

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.

See the standard library documentation for more information on exception groups.

Catching exceptions

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 sole argument.

The argument to catch() must be a dict (or any Mapping) where each key is either an exception class or an iterable of exception classes. Each value must be a callable that takes a single positional argument. The handler will be called at most once, with an exception group as an argument which will contain all the exceptions that are any of the given types, or their subclasses. The exception group may contain nested groups containing more matching exceptions.

Thus, the following Python 3.11+ code:

try:
    ...
except* (ValueError, KeyError) as excgroup:
    for exc in excgroup.exceptions:
        print('Caught exception:', type(exc))
except* RuntimeError:
    print('Caught runtime error')

would be written with this backport like this:

from exceptiongroup import BaseExceptionGroup, catch

def value_key_err_handler(excgroup: BaseExceptionGroup) -> None:
    for exc in excgroup.exceptions:
        print('Caught exception:', type(exc))

def runtime_err_handler(exc: BaseExceptionGroup) -> None:
    print('Caught runtime error')

with catch({
    (ValueError, KeyError): value_key_err_handler,
    RuntimeError: runtime_err_handler
}):
    ...

NOTE: Just like with except*, you cannot handle BaseExceptionGroup or ExceptionGroup with catch().

Suppressing exceptions

This library contains a backport of the contextlib.suppress() context manager from Python 3.12.1. It allows you to selectively ignore certain exceptions, even when they’re inside exception groups:

from exceptiongroup import suppress

with suppress(RuntimeError):
    raise ExceptionGroup("", [RuntimeError("boo")])

Notes on monkey patching

To make exception groups render properly when an unhandled exception group is being printed out, this package does two things when it is imported on any Python version earlier than 3.11:

  1. The traceback.TracebackException class is monkey patched to store extra information about exception groups (in __init__()) and properly format them (in format())

  2. An exception hook is installed at sys.excepthook, provided that no other hook is already present. This hook causes the exception to be formatted using traceback.TracebackException rather than the built-in rendered.

If sys.exceptionhook is found to be set to something else than the default when exceptiongroup is imported, no monkeypatching is done at all.

To prevent the exception hook and patches from being installed, set the environment variable EXCEPTIONGROUP_NO_PATCH to 1.

Formatting exception groups

Normally, the monkey patching applied by this library on import will cause exception groups to be printed properly in tracebacks. But in cases when the monkey patching is blocked by a third party exception hook, or monkey patching is explicitly disabled, you can still manually format exceptions using the special versions of the traceback functions, like format_exception(), listed at the top of this page. They work just like their counterparts in the traceback module, except that they use a separately patched subclass of TracebackException to perform the rendering.

Particularly in cases where a library installs its own exception hook, it is recommended to use these special versions to do the actual formatting of exceptions/tracebacks.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

exceptiongroup-1.3.1.tar.gz (30.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

exceptiongroup-1.3.1-py3-none-any.whl (16.7 kB view details)

Uploaded Python 3

File details

Details for the file exceptiongroup-1.3.1.tar.gz.

File metadata

  • Download URL: exceptiongroup-1.3.1.tar.gz
  • Upload date:
  • Size: 30.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for exceptiongroup-1.3.1.tar.gz
Algorithm Hash digest
SHA256 8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219
MD5 f88685ec75c5715111d65aeae28c9322
BLAKE2b-256 507966800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9

See more details on using hashes here.

Provenance

The following attestation bundles were made for exceptiongroup-1.3.1.tar.gz:

Publisher: publish.yml on agronholm/exceptiongroup

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file exceptiongroup-1.3.1-py3-none-any.whl.

File metadata

  • Download URL: exceptiongroup-1.3.1-py3-none-any.whl
  • Upload date:
  • Size: 16.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for exceptiongroup-1.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598
MD5 ae266455b7797174f2d91304ccaf1275
BLAKE2b-256 8a0e97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e

See more details on using hashes here.

Provenance

The following attestation bundles were made for exceptiongroup-1.3.1-py3-none-any.whl:

Publisher: publish.yml on agronholm/exceptiongroup

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page