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

问题描述

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

这是我想做的事的一个例子:

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)