title: What is the proper way to type hint the return value of an @asynccontextmanager?
body: <p>What is the proper way to add type hints for the return of a function with the <code>@asynccontextmanager</code> decorator?  Here are two attempts I made that both fail.</p>
  <pre class="lang-py prettyprint-override"><code>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() -&gt; str:
      yield &quot;hello&quot;
  
  
  @asynccontextmanager
  async def return_AsyncContextManager() -&gt; AsyncContextManager[str]:
      yield &quot;world&quot;
  </code></pre>
  <p>For both <code>i</code> and <code>j</code> <a href="https://github.com/microsoft/pylance-release" rel="nofollow noreferrer">Pylance</a> in vscode shows type <code>Any</code>.  Other ideas I've considered:</p>
  <ul>
  <li>I thought maybe I could pass in the type info to the decorator itself (like <code>@asynccontextmanager(cls=str)</code>, but I can't find any examples of that, or any description of the args I could pass in.</li>
  <li><code>async with return_str() as i: # type: str</code> doesn'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.</li>
  <li>I tried to create an <code>AsyncContextManager</code> class with <code>__aenter()__</code> and <code>__aexit()__</code> 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.</li>
  </ul>
  <p>Here's a screencap of me hovering the <code>return_AsyncContextManager()</code> function, and showing the Pylance popup saying it returns <code>AsyncContextManager[_T]</code>
  <a href="https://i.stack.imgur.com/FBmOU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FBmOU.png" alt="enter image description here" /></a></p>