Skip to content

fix(crons): Fix type hints for monitor decorator #2944

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 44 additions & 13 deletions sentry_sdk/crons/_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@

if TYPE_CHECKING:
from typing import (
Any,
Awaitable,
Callable,
cast,
overload,
ParamSpec,
TypeVar,
Union,
Expand All @@ -17,22 +20,50 @@


class MonitorMixin:
def __call__(self, fn):
# type: (Callable[P, R]) -> Callable[P, Union[R, Awaitable[R]]]
if iscoroutinefunction(fn):
if TYPE_CHECKING:

@overload
def __call__(self, fn):
# type: (Callable[P, Awaitable[Any]]) -> Callable[P, Awaitable[Any]]
# Unfortunately, mypy does not give us any reliable way to type check the
# return value of an Awaitable (i.e. async function) for this overload,
# since calling iscouroutinefunction narrows the type to Callable[P, Awaitable[Any]].
...

@wraps(fn)
async def inner(*args: "P.args", **kwargs: "P.kwargs"):
# type: (...) -> R
with self: # type: ignore[attr-defined]
return await fn(*args, **kwargs)
@overload
def __call__(self, fn):
# type: (Callable[P, R]) -> Callable[P, R]
...

def __call__(
self,
fn, # type: Union[Callable[P, R], Callable[P, Awaitable[Any]]]
):
# type: (...) -> Union[Callable[P, R], Callable[P, Awaitable[Any]]]
if iscoroutinefunction(fn):
return self._async_wrapper(fn)

else:
if TYPE_CHECKING:
fn = cast("Callable[P, R]", fn)
return self._sync_wrapper(fn)

def _async_wrapper(self, fn):
# type: (Callable[P, Awaitable[Any]]) -> Callable[P, Awaitable[Any]]
@wraps(fn)
async def inner(*args: "P.args", **kwargs: "P.kwargs"):
# type: (...) -> R
with self: # type: ignore[attr-defined]
return await fn(*args, **kwargs)

return inner

@wraps(fn)
def inner(*args: "P.args", **kwargs: "P.kwargs"):
# type: (...) -> R
with self: # type: ignore[attr-defined]
return fn(*args, **kwargs)
def _sync_wrapper(self, fn):
# type: (Callable[P, R]) -> Callable[P, R]
@wraps(fn)
def inner(*args: "P.args", **kwargs: "P.kwargs"):
# type: (...) -> R
with self: # type: ignore[attr-defined]
return fn(*args, **kwargs)

return inner