原始代码:
import functoolsasync def do_sth(f, gs, kw):print(f.__name__, gs, kw)def my_deco(func):@functools.wraps(func)async def wrapper(*args, **kw):await do_sth(func, args, kw)return await func(*args, **kw)return wrapper@my_deco
async def foo():print('............')
添加类型注解后的代码:
import sys
import functools
from typing import Callable, TypeVar, Awaitableif sys.version_info >= (3, 10):from typing import ParamSpec
else:# pip install typing_extensionsfrom typing_extensions import ParamSpecT = TypeVar("T")
P = ParamSpec("P")async def do_sth(f, gs, kw) -> None:print(f.__name__, gs, kw)def my_deco(func: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]:@functools.wraps(func)async def wrapper(*args, **kw) -> T:await do_sth(func, args, kw)return await func(*args, **kw)return wrapper@my_deco
async def foo() -> None:print("............")
参考:decorators cannot get type hints for async function return values · python/typing · Discussion #1284 · GitHub