Skip to content

decorators cannot get type hints for async function return values #1283

@mkdir700

Description

@mkdir700

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

image

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)

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: otherOther topics not covered

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions