如何在Python 3.7中注释异步函数的装饰器类型?

Ste*_*alt 3 python python-3.x python-asyncio mypy

我想为异步函数编写一个装饰器。如何注释装饰器定义的类型?

这是我想做的一个例子:

from typing import TypeVar # will Awaitable help?
AsyncFn = TypeVar('AsyncFn') # how to narrow this type definition down to async functions?

def my_decorator(to_decorate: AsyncFn) -> AsyncFn:
    async def decorated(*args, **kwargs): # mypy keeps saying "Function is missing a type"
       return await to_decorate(*args, **kwargs)

@my_decorator
async def foo(bar: int) -> str:
    return f"async: {bar}"

@my_decorator
async def quux(spam: str, **eggs: str) -> None:
    return

foo(1) # should check
foo("baz") # mypy should yell
quux("spam") # should check
quux(1) # mypy should complain
quux(spam="lovely", eggs="plentiful") # ok
quux(spam=1, eggs=0) # mypy should throw a fit
Run Code Online (Sandbox Code Playgroud)

Paw*_*bin 7

函数async是返回Awaitable.

Python 3.10中ParamSpec引入了函数装饰器的完整类型注释async

from typing import Awaitable, Callable, ParamSpec, TypeVar

T = TypeVar("T")
P = ParamSpec("P")


def decorator(fn: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]:
    async def decorated(*args: P.args, **kwargs: P.kwargs) -> T:
        return await fn(*args, **kwargs)

    return decorated
Run Code Online (Sandbox Code Playgroud)

在Python 3.7中可以从typing_extensionsParamSpec导入。