Generator created in async function is actually an async_generator at runtime #10827
-
|
Code sample in pyright playground import asyncio
from collections.abc import AsyncGenerator
from typing import reveal_type
async def values() -> AsyncGenerator[int]:
yield 1
yield 2
yield 3
async def run() -> list[int]:
bar = ([foo async for foo in values()] for _ in range(2))
reveal_type(bar) # Runtime type is 'async_generator'
return next(bar) # TypeError: 'async_generator' object is not an iterator
asyncio.run(run())I'm confused by how generators work in async functions. mypy and Pyright agree that |
Beta Was this translation helpful? Give feedback.
Answered by
JelleZijlstra
Aug 21, 2025
Replies: 1 comment 6 replies
-
|
Hmm, I wasn't aware that any generator created within an async function's body is automatically created as async. Do you know if that behavior is documented? |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This happens only if the genexp contains an async listcomp inside of it:
This makes sense because the inner listcomp is async and therefore must be evaluated within an async context. It's not clearly documented, though: https://docs.python.org/3.14/reference/expressions.html#generator-expressions says "If a generator expression contains either async for clauses or await expressions it is called an asynchronous generator expression. An async…