Skip to content

Annotating the decorator with arguments that works for both sync/async functions #1847

Answered by erictraut
Galtozzy asked this question in Q&A
Discussion options

You must be logged in to vote

Here's a potential solution. It type checks without errors in pyright. Mypy produces a few overload-related errors that appear to be false positives, so you could add # type: ignore comments to suppress them.

Code sample in pyright playground

from typing import Awaitable, Callable, Protocol, overload
from typing_extensions import TypeIs
from inspect import iscoroutinefunction
from functools import wraps

def is_coroutine[**P, R](
    func: Callable[P, R | Awaitable[R]],
) -> TypeIs[Callable[P, Awaitable[R]]]:
    return iscoroutinefunction(func)

class SyncOrAsync(Protocol):
    @overload
    def __call__[**P, R](
        self, _func: Callable[P, Awaitable[R]]
    ) -> Callable[P, Awaitable[

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Galtozzy
Comment options

Answer selected by Galtozzy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants