Skip to content

Commit 4729d53

Browse files
fix(crons): Fix type hints for monitor decorator (#2944)
Fixes GH-2939
1 parent 669ed17 commit 4729d53

File tree

1 file changed

+44
-13
lines changed

1 file changed

+44
-13
lines changed

sentry_sdk/crons/_decorator.py

Lines changed: 44 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@
55

66
if TYPE_CHECKING:
77
from typing import (
8+
Any,
89
Awaitable,
910
Callable,
11+
cast,
12+
overload,
1013
ParamSpec,
1114
TypeVar,
1215
Union,
@@ -17,22 +20,50 @@
1720

1821

1922
class MonitorMixin:
20-
def __call__(self, fn):
21-
# type: (Callable[P, R]) -> Callable[P, Union[R, Awaitable[R]]]
22-
if iscoroutinefunction(fn):
23+
if TYPE_CHECKING:
24+
25+
@overload
26+
def __call__(self, fn):
27+
# type: (Callable[P, Awaitable[Any]]) -> Callable[P, Awaitable[Any]]
28+
# Unfortunately, mypy does not give us any reliable way to type check the
29+
# return value of an Awaitable (i.e. async function) for this overload,
30+
# since calling iscouroutinefunction narrows the type to Callable[P, Awaitable[Any]].
31+
...
2332

24-
@wraps(fn)
25-
async def inner(*args: "P.args", **kwargs: "P.kwargs"):
26-
# type: (...) -> R
27-
with self: # type: ignore[attr-defined]
28-
return await fn(*args, **kwargs)
33+
@overload
34+
def __call__(self, fn):
35+
# type: (Callable[P, R]) -> Callable[P, R]
36+
...
37+
38+
def __call__(
39+
self,
40+
fn, # type: Union[Callable[P, R], Callable[P, Awaitable[Any]]]
41+
):
42+
# type: (...) -> Union[Callable[P, R], Callable[P, Awaitable[Any]]]
43+
if iscoroutinefunction(fn):
44+
return self._async_wrapper(fn)
2945

3046
else:
47+
if TYPE_CHECKING:
48+
fn = cast("Callable[P, R]", fn)
49+
return self._sync_wrapper(fn)
50+
51+
def _async_wrapper(self, fn):
52+
# type: (Callable[P, Awaitable[Any]]) -> Callable[P, Awaitable[Any]]
53+
@wraps(fn)
54+
async def inner(*args: "P.args", **kwargs: "P.kwargs"):
55+
# type: (...) -> R
56+
with self: # type: ignore[attr-defined]
57+
return await fn(*args, **kwargs)
58+
59+
return inner
3160

32-
@wraps(fn)
33-
def inner(*args: "P.args", **kwargs: "P.kwargs"):
34-
# type: (...) -> R
35-
with self: # type: ignore[attr-defined]
36-
return fn(*args, **kwargs)
61+
def _sync_wrapper(self, fn):
62+
# type: (Callable[P, R]) -> Callable[P, R]
63+
@wraps(fn)
64+
def inner(*args: "P.args", **kwargs: "P.kwargs"):
65+
# type: (...) -> R
66+
with self: # type: ignore[attr-defined]
67+
return fn(*args, **kwargs)
3768

3869
return inner

0 commit comments

Comments
 (0)