exceptiongroup


Nameexceptiongroup JSON
Version 1.2.1 PyPI version JSON
download
home_pageNone
SummaryBackport of PEP 654 (exception groups)
upload_time2024-04-18 21:19:14
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            .. image:: https://github.com/agronholm/exceptiongroup/actions/workflows/test.yml/badge.svg
  :target: https://github.com/agronholm/exceptiongroup/actions/workflows/test.yml
  :alt: Build Status
.. image:: https://coveralls.io/repos/github/agronholm/exceptiongroup/badge.svg?branch=main
  :target: https://coveralls.io/github/agronholm/exceptiongroup?branch=main
  :alt: 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.

.. _standard library documentation: https://docs.python.org/3/library/exceptions.html

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:

.. code-block:: python

    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:

.. code-block:: python

    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:

.. code-block:: python

    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:

#. The  ``traceback.TracebackException`` class is monkey patched to store extra
   information about exception groups (in ``__init__()``) and properly format them (in
   ``format()``)
#. 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.

.. _PEP 654: https://www.python.org/dev/peps/pep-0654/


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "exceptiongroup",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": null,
    "author": null,
    "author_email": "Alex Gr\u00f6nholm <alex.gronholm@nextday.fi>",
    "download_url": "https://files.pythonhosted.org/packages/a0/65/d66b7fbaef021b3c954b3bbb196d21d8a4b97918ea524f82cfae474215af/exceptiongroup-1.2.1.tar.gz",
    "platform": null,
    "description": ".. image:: https://github.com/agronholm/exceptiongroup/actions/workflows/test.yml/badge.svg\n  :target: https://github.com/agronholm/exceptiongroup/actions/workflows/test.yml\n  :alt: Build Status\n.. image:: https://coveralls.io/repos/github/agronholm/exceptiongroup/badge.svg?branch=main\n  :target: https://coveralls.io/github/agronholm/exceptiongroup?branch=main\n  :alt: Code Coverage\n\nThis is a backport of the ``BaseExceptionGroup`` and ``ExceptionGroup`` classes from\nPython 3.11.\n\nIt contains the following:\n\n* The  ``exceptiongroup.BaseExceptionGroup`` and ``exceptiongroup.ExceptionGroup``\n  classes\n* A utility function (``exceptiongroup.catch()``) for catching exceptions possibly\n  nested in an exception group\n* Patches to the ``TracebackException`` class that properly formats exception groups\n  (installed on import)\n* An exception hook that handles formatting of exception groups through\n  ``TracebackException`` (installed on import)\n* Special versions of some of the functions from the ``traceback`` module, modified to\n  correctly handle exception groups even when monkey patching is disabled, or blocked by\n  another custom exception hook:\n\n  * ``traceback.format_exception()``\n  * ``traceback.format_exception_only()``\n  * ``traceback.print_exception()``\n  * ``traceback.print_exc()``\n* A backported version of ``contextlib.suppress()`` from Python 3.12.1 which also\n  handles suppressing exceptions inside exception groups\n\nIf this package is imported on Python 3.11 or later, the built-in implementations of the\nexception group classes are used instead, ``TracebackException`` is not monkey patched\nand the exception hook won't be installed.\n\nSee the `standard library documentation`_ for more information on exception groups.\n\n.. _standard library documentation: https://docs.python.org/3/library/exceptions.html\n\nCatching exceptions\n===================\n\nDue to the lack of the ``except*`` syntax introduced by `PEP 654`_ in earlier Python\nversions, you need to use ``exceptiongroup.catch()`` to catch exceptions that are\npotentially nested inside an exception group. This function returns a context manager\nthat calls the given handler for any exceptions matching the sole argument.\n\nThe argument to ``catch()`` must be a dict (or any ``Mapping``) where each key is either\nan exception class or an iterable of exception classes. Each value must be a callable\nthat takes a single positional argument. The handler will be called at most once, with\nan exception group as an argument which will contain all the exceptions that are any\nof the given types, or their subclasses. The exception group may contain nested groups\ncontaining more matching exceptions.\n\nThus, the following Python 3.11+ code:\n\n.. code-block:: python\n\n    try:\n        ...\n    except* (ValueError, KeyError) as excgroup:\n        for exc in excgroup.exceptions:\n            print('Caught exception:', type(exc))\n    except* RuntimeError:\n        print('Caught runtime error')\n\nwould be written with this backport like this:\n\n.. code-block:: python\n\n    from exceptiongroup import BaseExceptionGroup, catch\n\n    def value_key_err_handler(excgroup: BaseExceptionGroup) -> None:\n        for exc in excgroup.exceptions:\n            print('Caught exception:', type(exc))\n\n    def runtime_err_handler(exc: BaseExceptionGroup) -> None:\n        print('Caught runtime error')\n\n    with catch({\n        (ValueError, KeyError): value_key_err_handler,\n        RuntimeError: runtime_err_handler\n    }):\n        ...\n\n**NOTE**: Just like with ``except*``, you cannot handle ``BaseExceptionGroup`` or\n``ExceptionGroup`` with ``catch()``.\n\nSuppressing exceptions\n======================\n\nThis library contains a backport of the ``contextlib.suppress()`` context manager from\nPython 3.12.1. It allows you to selectively ignore certain exceptions, even when they're\ninside exception groups:\n\n.. code-block:: python\n\n    from exceptiongroup import suppress\n\n    with suppress(RuntimeError):\n        raise ExceptionGroup(\"\", [RuntimeError(\"boo\")])\n\nNotes on monkey patching\n========================\n\nTo make exception groups render properly when an unhandled exception group is being\nprinted out, this package does two things when it is imported on any Python version\nearlier than 3.11:\n\n#. The  ``traceback.TracebackException`` class is monkey patched to store extra\n   information about exception groups (in ``__init__()``) and properly format them (in\n   ``format()``)\n#. An exception hook is installed at ``sys.excepthook``, provided that no other hook is\n   already present. This hook causes the exception to be formatted using\n   ``traceback.TracebackException`` rather than the built-in rendered.\n\nIf ``sys.exceptionhook`` is found to be set to something else than the default when\n``exceptiongroup`` is imported, no monkeypatching is done at all.\n\nTo prevent the exception hook and patches from being installed, set the environment\nvariable ``EXCEPTIONGROUP_NO_PATCH`` to ``1``.\n\nFormatting exception groups\n---------------------------\n\nNormally, the monkey patching applied by this library on import will cause exception\ngroups to be printed properly in tracebacks. But in cases when the monkey patching is\nblocked by a third party exception hook, or monkey patching is explicitly disabled,\nyou can still manually format exceptions using the special versions of the ``traceback``\nfunctions, like ``format_exception()``, listed at the top of this page. They work just\nlike their counterparts in the ``traceback`` module, except that they use a separately\npatched subclass of ``TracebackException`` to perform the rendering.\n\nParticularly in cases where a library installs its own exception hook, it is recommended\nto use these special versions to do the actual formatting of exceptions/tracebacks.\n\n.. _PEP 654: https://www.python.org/dev/peps/pep-0654/\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Backport of PEP 654 (exception groups)",
    "version": "1.2.1",
    "project_urls": {
        "Changelog": "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst",
        "Issue Tracker": "https://github.com/agronholm/exceptiongroup/issues",
        "Source code": "https://github.com/agronholm/exceptiongroup"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "019079fe92dd413a9cab314ef5c591b5aa9b9ba787ae4cadab75055b0ae00b33",
                "md5": "12b64dafc43dd1f5d3a581fb84fd67d8",
                "sha256": "5258b9ed329c5bbdd31a309f53cbfb0b155341807f6ff7606a1e801a891b29ad"
            },
            "downloads": -1,
            "filename": "exceptiongroup-1.2.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "12b64dafc43dd1f5d3a581fb84fd67d8",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 16458,
            "upload_time": "2024-04-18T21:19:11",
            "upload_time_iso_8601": "2024-04-18T21:19:11.799138Z",
            "url": "https://files.pythonhosted.org/packages/01/90/79fe92dd413a9cab314ef5c591b5aa9b9ba787ae4cadab75055b0ae00b33/exceptiongroup-1.2.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a065d66b7fbaef021b3c954b3bbb196d21d8a4b97918ea524f82cfae474215af",
                "md5": "4b18d11e20aadce2e87accccf434b1c4",
                "sha256": "a4785e48b045528f5bfe627b6ad554ff32def154f42372786903b7abcfe1aa16"
            },
            "downloads": -1,
            "filename": "exceptiongroup-1.2.1.tar.gz",
            "has_sig": false,
            "md5_digest": "4b18d11e20aadce2e87accccf434b1c4",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 28717,
            "upload_time": "2024-04-18T21:19:14",
            "upload_time_iso_8601": "2024-04-18T21:19:14.118156Z",
            "url": "https://files.pythonhosted.org/packages/a0/65/d66b7fbaef021b3c954b3bbb196d21d8a4b97918ea524f82cfae474215af/exceptiongroup-1.2.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-18 21:19:14",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "agronholm",
    "github_project": "exceptiongroup",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "exceptiongroup"
}
        
Elapsed time: 0.32400s