How agronholm/exceptiongroup works
Project Type and Purpose
• This is a backport library for Python’s BaseExceptionGroup/ExceptionGroup (PEP 654).
• It provides:
• Core exception group classes
• A catch() context‐manager API
• A suppress() API
• Monkey‐patching of traceback.TracebackException and sys.excepthook
• Special versions of traceback.* functions
File Structure
• src/exceptiongroup/: the package root
• _exceptions.py → defines BaseExceptionGroup & ExceptionGroup
• _catch.py → implements catch()
• _suppress.py → implements suppress()
• _formatting.py → monkey patches TracebackException & provides format_* overrides
• __init__.py → imports and installs monkey patches on import
• py.typed → indicates PEP 561 typing support
• tests/: covers unit tests for each module
• CI/config files (.github/, pyproject.toml, pre‐commit, etc.)
Extract Key Architectural Elements from README
• “On import, if Python <3.11, install patches; otherwise no‐ops.”
• Two extension points: sys.excepthook override & patched TracebackException.
• Exposed public API: catch(), suppress(), ExceptionGroup classes, and patched traceback functions.
Main Components & Their Relationships
A. Public API Layer
– exceptiongroup.catch() (context manager)
– exceptiongroup.suppress() (context manager)
– exceptiongroup.BaseExceptionGroup & ExceptionGroup classes
– fallback or no‐op behavior on Python 3.11+
B. Core Logic Layer
– _exceptions: exception group data structures
– _catch: logic for iterating and dispatching handlers
– _suppress: context manager that re‐raises filtered groups
C. Formatting / Monkey‐Patch Layer
– _formatting:
• Patches traceback.TracebackException.__init__ & .format()
• Implements format_exception, format_exception_only, print_exception, print_exc
– sys.excepthook hook installation
– Environment‐based toggle (EXCEPTIONGROUP_NO_PATCH)
D. Test Suite
– tests for each corner: catching, suppressing, formatting, hook behavior, Python 3.11 compatibility.
Architectural Patterns & Design Principles
• Separation of Concerns:
• Data Structures (_exceptions) vs. Control Flow (_catch/_suppress) vs. I/O/Presentation (_formatting).
• Lazy initialization: patches applied at import only once, gated by environment and Python version.
• Backport/Adapter pattern: adapts new language features for older runtimes.
• Context‐manager-based APIs for resource‐like semantics (catch, suppress).