You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
hasattr on __await__ should narrow the type to Awaitable
Code or Screenshots
fromtypingimportTYPE_CHECKING, Callable, TypeVar, Awaitable, Union, overload, Any, castfromtyping_extensionsimportParamSpecP=ParamSpec("P")
T=TypeVar("T")
@overloadasyncdefawait_result(func: Callable[P, Awaitable[T]], *args: P.args, **kwargs: P.kwargs) ->T:
...
@overloadasyncdefawait_result(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) ->T:
...
asyncdefawait_result(func: Callable[P, Union[T, Awaitable[T]]], *args: P.args, **kwargs: P.kwargs) ->T:
"""If func returns an awaitable, await it. :param func: The function to run. :type func: callable :param args: The positional arguments to pass to the function. :type args: list :rtype: any :return: The result of the function """result: Union[T, Awaitable[T]] =func(*args, **kwargs)
ifhasattr(result, "__await__"):
returnawaitresultreturnresultdefsync_callback(input: int) ->int:
returninput+1asyncdefasync_callback(input: int) ->int:
returninput+1asyncdefmain():
awaitawait_result(sync_callback, 1)
awaitawait_result(async_callback, 1)
Triggers:
decorator_typing.py:28:22 - error: "object*" is not awaitable (reportGeneralTypeIssues)
decorator_typing.py:29:12 - error: Expression of type "T@await_result | Awaitable[T@await_result]" cannot be assigned to return type "T@await_result"
This isn't one of the type guard patterns that pyright supports. For a full list of supported type guard patterns, refer to this documentation.
We do occasionally entertain the addition of new type guard support, but it's a high bar. Each new pattern requires custom logic and potentially slows down type analysis for all code. For that reason, we add new type guard support only when we have strong signal that it's a common idiom. I don't think the hasattr(x, '__async__') pattern is common. This is the first time I've ever seen it used.
I recommend that you use a user-defined type guard. For details, refer to PEP 647.
Describe the bug
hasattr
on__await__
should narrow the type toAwaitable
Code or Screenshots
Triggers:
Pyright 1.1.325. Mypy is happy with it:
https://mypy-play.net/?mypy=latest&python=3.11&gist=2bcc59c72d884b386a01bd545d8a6a83
Side note, right now I'm casting and all is fine :)
The text was updated successfully, but these errors were encountered: