decorators cannot get type hints for async function return values #1284
-
I use a decorator to get the return value type of a synchronous function, it's ok. this code: import asyncio
from functools import wraps
from typing import Any, Awaitable, Callable, TypeVar, ParamSpec, Coroutine
T = TypeVar("T") # the callable/awaitable return type
P = ParamSpec("P") # the callable parameters
def sync_dec(message: Any) -> Callable[[Callable[P, T]], Callable[P, T]]:
def wrapper(f: Callable[P, T]) -> Callable[P, T]:
@wraps(f)
def inner(*args: Any, **kwargs: Any) -> T:
print(message)
return f(*args, **kwargs)
return inner
return wrapper
@sync_dec("hello")
def f(x: int, y: int) -> int:
return x + y
f() # error: missing positional argument "x" and "y" in call to "f"
f(1, 2) # ok but,I can't get the return value type hint of an async function using a decorator. this code: def async_dec(message: Any):
def wrapper(f: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]:
async def inner(*args: Any, **kwargs: Any) -> T:
print(message)
return await f(*args, **kwargs)
return inner
return wrapper
@async_dec("hello")
async def f3(a: int, b: int) -> int:
return a + b
async def run():
await f3() # missing positional argument "x" and "y" in call to "f3"
r = await f3(1, 2) |
Beta Was this translation helpful? Give feedback.
Answered by
JelleZijlstra
Nov 5, 2022
Replies: 1 comment 1 reply
-
This is because |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
mkdir700
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is because
async_dec
is missing a return type. If I add a return type (Callable[[Callable[P, Awaitable[T]]], Callable[P, Awaitable[T]]]
), both mypy and pyright correctly infer thatr
is anint
.