python async_error ai_generated true

TypeError: 'async_generator' object is not iterable

ID: python/typeerror-async-generator-not-iterable

Also available as: JSON · Markdown
93%Fix Rate
91%Confidence
40Evidence
2018-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Synchronous iteration patterns (for, list(), list comprehension) cannot consume async generators. Use 'async for' or async list comprehensions instead. Must be inside an async function.

generic

Workarounds

  1. 95% success Use 'async for' loop to consume the async generator
    async for item in async_gen(): process(item). This is the primary way to consume async generators. Must be inside an async function.

    Sources: https://docs.python.org/3/reference/compound_stmts.html#the-async-for-statement

  2. 93% success Use async list comprehension to collect all values
    results = [x async for x in async_gen()]. The 'async for' inside the comprehension handles the async iteration protocol. Must be inside an async function.

    Sources: https://docs.python.org/3/reference/expressions.html#asynchronous-comprehensions

  3. 90% success Create a helper function to materialize async generators
    async def collect(gen): return [x async for x in gen]. Then: results = await collect(async_gen()). This utility wraps the async comprehension pattern for reuse across the codebase.

Dead Ends

Common approaches that don't work:

  1. Wrapping in list() to force evaluation 95% fail

    list() is a synchronous function that uses the __iter__ protocol. Async generators implement __aiter__, not __iter__. list(async_gen()) fails with the same TypeError because the protocols are incompatible.

  2. Adding await before the generator call 90% fail

    Async generators are not awaitables. They yield multiple values asynchronously. 'await' is for coroutines (single return value), not generators (multiple yield values). 'await async_gen()' raises TypeError: object async_generator can't be used in 'await' expression.

  3. Using synchronous list comprehension [x for x in async_gen()] 95% fail

    Synchronous list comprehensions use the sync iteration protocol (__iter__/__next__). They cannot iterate async generators. The comprehension produces the same TypeError.

Error Chain

Frequently confused with: