What is the proper way to add type hints for the return of a function with the @asynccontextmanager decorator? Here are two attempts I made that both fail.
from contextlib import asynccontextmanager
from typing import AsyncContextManager
async def caller():
async with return_str() as i:
print(i)
async with return_AsyncContextManager() as j:
print(j)
@asynccontextmanager
async def return_str() -> str:
yield "hello"
@asynccontextmanager
async def return_AsyncContextManager() -> AsyncContextManager[str]:
yield "world"
For both i and j Pylance in vscode shows type Any. Other ideas I've considered:
- I thought maybe I could pass in the type info to the decorator itself (like
@asynccontextmanager(cls=str), but I can't find any examples of that, or any description of the args I could pass in. async with return_str() as i: # type: strdoesn't work either. Even if it did, I'd rather hint at the function definition, not at every invocation. Type comments are not very DRY.- I tried to create an
AsyncContextManagerclass with__aenter()__and__aexit()__functions, but was not successful. I would fall back to that if it worked, but I'd prefer to make the decorator work because it's much more concise.
Here's a screencap of me hovering the return_AsyncContextManager() function, and showing the Pylance popup saying it returns AsyncContextManager[_T]

