Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sanderegg committed Dec 2, 2024
1 parent 12af567 commit af515c5
Showing 1 changed file with 22 additions and 19 deletions.
41 changes: 22 additions & 19 deletions packages/service-library/src/servicelib/exception_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from collections.abc import Callable
from datetime import datetime
from functools import wraps
from typing import Final, ParamSpec, TypeVar
from typing import Any, Final, ParamSpec, TypeVar

from pydantic import BaseModel, Field, NonNegativeFloat, PrivateAttr

Expand Down Expand Up @@ -73,28 +73,31 @@ def else_reset(self) -> None:
P = ParamSpec("P")
R = TypeVar("R")

F = TypeVar("F", bound=Callable[..., Any])

def silence_exceptions(
exceptions: tuple[type[BaseException], ...]
) -> Callable[[Callable[P, R]], Callable[P, R]]:
def decorator(func: Callable[..., R]) -> Callable[..., R]:
@wraps(func)
def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
try:
return func(*args, **kwargs)
except exceptions:
return None

@wraps(func)
async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
def silence_exceptions(exceptions: tuple[type[BaseException], ...]) -> Callable[[F], F]:
def _decorator(func_or_coro: F) -> F:

if inspect.iscoroutinefunction(func_or_coro):

@wraps(func_or_coro)
async def _async_wrapper(*args, **kwargs) -> Any:
try:
assert inspect.iscoroutinefunction(func_or_coro) # nosec
return await func_or_coro(*args, **kwargs)
except exceptions:
return None

return _async_wrapper # type: ignore[return-value] # decorators typing is hard

@wraps(func_or_coro)
def _sync_wrapper(*args, **kwargs) -> Any:
try:
assert inspect.iscoroutinefunction(func) # nosec
return await func(*args, **kwargs)
return func_or_coro(*args, **kwargs)
except exceptions:
return None

if inspect.iscoroutinefunction(func):
return async_wrapper # type: ignore
return sync_wrapper # type: ignore
return _sync_wrapper # type: ignore[return-value] # decorators typing is hard

return decorator
return _decorator

0 comments on commit af515c5

Please sign in to comment.