Skip to content

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

Closed

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

Activity

  1. locked and limited conversation to collaborators on Nov 5, 2022
  2. converted this issue into a discussion #1284 on Nov 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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