Skip to content

Commit

Permalink
🎨Typing issues (#11)
Browse files Browse the repository at this point in the history
* 🎨Typing issues

* Make arguments keyword-only

* Exception -> BaseException

* 🚨thx black
  • Loading branch information
lord-haffi committed Mar 8, 2024
1 parent 38f8f62 commit 448d79c
Show file tree
Hide file tree
Showing 13 changed files with 198 additions and 127 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,4 @@ dmypy.json
# vscode settings
.vscode/

src/_your_package_version.py
src/_error_handler_version.py
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,13 @@ logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, force=True)
logger = logging.root
op = aiostream.stream.iterate(range(10))


def log_error(error: Exception, num: int):
"""Only log error and reraise it"""
logger.error("double_only_odd_nums_except_5 failed for input %d. ", num)
raise error


@error_handler.decorator(on_error=log_error)
async def double_only_odd_nums_except_5(num: int) -> int:
if num % 2 == 0:
Expand All @@ -59,13 +61,16 @@ async def double_only_odd_nums_except_5(num: int) -> int:
num *= 2
return num


def catch_value_errors(error: Exception, _: int):
if not isinstance(error, ValueError):
raise error


def log_success(result_num: int, provided_num: int):
logger.info("Success: %d -> %d", provided_num, result_num)


op = op | error_handler.pipe.map(
double_only_odd_nums_except_5,
on_error=catch_value_errors,
Expand Down
14 changes: 3 additions & 11 deletions src/error_handler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,9 @@
from typing import TYPE_CHECKING

from .context_manager import context_manager
from .decorator import decorator, retry_on_error
from .types import (
ERRORED,
UNSET,
AsyncFunctionType,
ErroredType,
FunctionType,
SecuredAsyncFunctionType,
SecuredFunctionType,
UnsetType,
)
from .decorator import decorator, decorator_as_result, retry_on_error
from .result import NegativeResult, PositiveResult, ResultType
from .types import UNSET, AsyncFunctionType, FunctionType, SecuredAsyncFunctionType, SecuredFunctionType, UnsetType

if TYPE_CHECKING:
from . import pipe, stream
Expand Down
4 changes: 3 additions & 1 deletion src/error_handler/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ class ErrorCallback(Callback[_P, _T]):
signature.
"""

_CALLBACK_ERROR_PARAM = inspect.Parameter("error", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Exception)
_CALLBACK_ERROR_PARAM = inspect.Parameter(
"error", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=BaseException
)

@classmethod
def from_callable(
Expand Down
7 changes: 4 additions & 3 deletions src/error_handler/context_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@
from typing import Any, Callable, Iterator

from .callback import Callback, ErrorCallback
from .core import Catcher
from .core import Catcher, ContextCatcher
from .types import UnsetType


# pylint: disable=unsubscriptable-object
@contextmanager
def context_manager(
*,
on_success: Callable[[], Any] | None = None,
on_error: Callable[[Exception], Any] | None = None,
on_error: Callable[[BaseException], Any] | None = None,
on_finalize: Callable[[], Any] | None = None,
suppress_recalling_on_error: bool = True,
) -> Iterator[Catcher[UnsetType]]:
Expand All @@ -28,7 +29,7 @@ def context_manager(
If suppress_recalling_on_error is True, the on_error callable will not be called if the error were already
caught by a previous catcher.
"""
catcher = Catcher[UnsetType](
catcher = ContextCatcher(
Callback.from_callable(on_success, return_type=Any) if on_success is not None else None,
ErrorCallback.from_callable(on_error, return_type=Any) if on_error is not None else None,
Callback.from_callable(on_finalize, return_type=Any) if on_finalize is not None else None,
Expand Down
16 changes: 10 additions & 6 deletions src/error_handler/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
ResultType,
ReturnValues,
)
from .types import ERRORED, UNSET, ErroredType, T, UnsetType
from .types import UNSET, T, UnsetType

_T = TypeVar("_T")
_U = TypeVar("_U")
Expand All @@ -43,15 +43,13 @@ def __init__(
on_success: Callback | None = None,
on_error: Callback | None = None,
on_finalize: Callback | None = None,
on_error_return_always: T | ErroredType = ERRORED,
suppress_recalling_on_error: bool = True,
raise_callback_errors: bool = True,
no_wrap_exception_group_when_reraise: bool = True,
):
self.on_success = on_success
self.on_error = on_error
self.on_finalize = on_finalize
self.on_error_return_always = on_error_return_always
self.suppress_recalling_on_error = suppress_recalling_on_error
"""
If this flag is set, the framework won't call the callbacks if the caught exception was already caught by
Expand Down Expand Up @@ -208,7 +206,7 @@ def secure_call( # type: ignore[return] # Because mypy is stupid, idk.
result = callable_to_secure(*args, **kwargs)
self._result = PositiveResult(result=result)
except BaseException as error: # pylint: disable=broad-exception-caught
self._result = NegativeResult(error=error, result=self.on_error_return_always)
self._result = NegativeResult(error=error)
return self.result

async def secure_await( # type: ignore[return] # Because mypy is stupid, idk.
Expand All @@ -227,9 +225,15 @@ async def secure_await( # type: ignore[return] # Because mypy is stupid, idk.
result = await awaitable_to_secure
self._result = PositiveResult(result=result)
except BaseException as error: # pylint: disable=broad-exception-caught
self._result = NegativeResult(error=error, result=self.on_error_return_always)
self._result = NegativeResult(error=error)
return self.result


class ContextCatcher(Catcher[UnsetType]):
"""
This class is a special case of the Catcher class. It is meant to use the context manager.
"""

@contextmanager
def secure_context(self) -> Iterator[Self]:
"""
Expand All @@ -245,4 +249,4 @@ def secure_context(self) -> Iterator[Self]:
yield self
self._result = PositiveResult(result=UNSET)
except BaseException as error: # pylint: disable=broad-exception-caught
self._result = NegativeResult(error=error, result=self.on_error_return_always)
self._result = NegativeResult(error=error)

0 comments on commit 448d79c

Please sign in to comment.