Skip to content

Commit

Permalink
utils:helpers - let ExceptionManager raise specific exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
MatteoCampinoti94 committed Nov 21, 2023
1 parent 953ee98 commit 66f526f
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions acacore/utils/helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from types import TracebackType
from typing import Optional
from typing import Sequence
from typing import Type


Expand All @@ -14,14 +15,16 @@ class ExceptionManager:
exception (Optional[BaseException]): The exception that was raised within the context, if any.
traceback (Optional[TracebackType]): The traceback associated with the exception, if any.
catch (tuple[Type[BaseException], ...]): Tuple of exceptions that should be caught instead of letting them rise.
allow (tuple[Type[BaseException], ...]): Tuple of exceptions that should be allowed to rise.
"""

__slots__ = ("exception", "traceback", "catch")
__slots__ = ("exception", "traceback", "catch", "allow")

def __init__(self, *catch: Type[BaseException]) -> None:
def __init__(self, *catch: Type[BaseException], allow: Optional[Sequence[Type[BaseException]]] = None) -> None:
self.exception: Optional[BaseException] = None
self.traceback: Optional[TracebackType] = None
self.catch: tuple[Type[BaseException], ...] = catch
self.allow: tuple[Type[BaseException], ...] = tuple(allow or [])

def __enter__(self) -> "ExceptionManager":
return self
Expand All @@ -34,4 +37,8 @@ def __exit__(
) -> bool:
self.exception = exc_val
self.traceback = exc_tb
return any(issubclass(exc_type, e) for e in self.catch) if exc_type else False

if not exc_type:
return False

return any(issubclass(exc_type, e) for e in self.catch) and not any(issubclass(exc_type, e) for e in self.allow)

0 comments on commit 66f526f

Please sign in to comment.