Context managers for controlling exception chaining.
Project description
Provides a different way of controlling exception chaining (the implicit __context__ and explicit __cause__) beyond just raise ... from ....
Versioning
This library’s version numbers follow the SemVer 2.0.0 specification.
Installation
pip install exceptioncontext
Usage
Import as needed:
from exceptioncontext import cause, context, suppress_context
Explicitly chain exception (set __cause__):
with cause(Exception("foo")):
raise Exception("bar")
Override implicitly chained exception (set __context__):
with context(Exception("foo")):
raise Exception("bar")
Manually control context suppression (set __suppress_context__):
with suppress_context(False):
raise Exception("foo")
Reduce repetition in code like
if some_condition:
raise SomeError("foo") from earlier_exception
elif other_condition:
raise OtherError("bar") from earlier_exception
else:
raise Exception("qux") from earlier_exception
by turning it into
with context(earlier_exception):
if some_condition:
raise SomeError("foo")
elif other_condition:
raise OtherError("bar")
else:
raise Exception("qux")
You now have more freedom in refactoring exception logic, because chaining is fully independent of the raise statement, and freely composable with other code:
with cause(earlier_exception):
helper_function_to_which_might_raise_an_exception()
Portability
Portable to all releases of both Python 3 and Python 2.
(The oldest tested is 2.5, but it will likely work on all Python 2 versions and probably on even earlier versions, when paired with something like `with-as-a-function <https://pypi.org/with-as-a-function>`_.)
On implementations of Python where setting the exception chaining attributes on an exception raises an AttributeError, exceptioncontext gracefully degrades to doing nothing.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for exceptioncontext-1.0.0-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 98f4e015b8e579bcffabc45f982d675ded1a403d060d99a5fa181188e5a9daf5 |
|
MD5 | d0bcc5b0e2a98379a12c5ff30bfd2e97 |
|
BLAKE2b-256 | f555da9d38f80c3b6a3237d07c4ff960bf534bf88ddcd74d80a94bc3233daa7f |