I'd like to write a decorator for an async function. How can I annotate the type of the decorator definition?
Here's an example of what I'd like to do:
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