Sub topic 3
Async generators as the source of a stream
This chapter assumes you know basic async/await and have run a coroutine with asyncio.run. It also assumes you know what a Python generator is. By the end you will be able to write an async generator, consume it, and explain why it is a good fit for streaming a response.
What an async generator is
An async generator is a function defined with async def that contains yield. Calling it does not run any of its body. It returns an object that produces values one at a time when you iterate over it with async for.
Between values, the generator can await slow work, such as a sleep, a database read, or a network call. While it waits, the event loop is free to serve other requests. This is the property a streaming endpoint needs. The generator produces a piece of output when it has one, and the server sends it on right away.
import asyncio
async def countdown(n: int):
try:
for i in range(n, 0, -1):
yield i
await asyncio.sleep(0.5)
finally:
print("generator closed")
async def main():
async for value in countdown(3):
print(value)
gen = countdown(10)
async for value in gen:
if value < 9:
break
await gen.aclose()
asyncio.run(main())The first loop prints 3, 2, 1, and then generator closed when the generator finishes. The second loop stops early with break. The generator is still suspended at its yield, so await gen.aclose() ends it explicitly, and the finally block runs.
How execution flows
The generator is lazy. Its body starts on the first request for a value and pauses at each yield. It resumes only when the consumer asks for the next value.
For a web server, the consumer is the framework. It pulls a chunk from your generator, writes it to the network, and then pulls the next one. Your generator never needs to hold the full response in memory.
Why not a list or a plain generator
| Source | Behavior in a streaming endpoint |
|---|---|
| List | The whole answer must exist before the first byte is sent. |
| Sync generator | Works, but Starlette runs it in a thread pool. A blocking call inside it still ties up a thread. |
| Async generator | Runs on the event loop. Waiting uses `await`, so no thread is blocked. |
LLM client libraries expose their streams as async iterators, so an async generator can wrap one directly. The Topic Spine's later chapters do exactly that.
Cleanup and cancellation
Put resource cleanup in try/finally. If the consumer stops early, as when a browser tab closes, the generator is closed at its current yield and the finally block runs. If the surrounding task is cancelled, asyncio.CancelledError is raised inside the generator at its current await. Do not swallow it with a bare except Exception that continues the loop. Let it propagate after any cleanup.
Common errors
TypeError: 'async_generator' object is not iterable: you usedforinstead ofasync for.SyntaxError: 'return' with value in async generator: an async generator can use a barereturnto stop, but it cannot return a value.- Calling
time.sleepinside the generator: this blocks the whole event loop, so every other request stalls. Useawait asyncio.sleep. - Awaiting the generator:
await countdown(3)fails, because the call returns a generator object and not a coroutine.
Exercise
In the countdown example, the second loop uses break and then calls await gen.aclose(). What would happen to the finally block if you never called aclose() and the generator were simply left suspended?
Show answer
The finally block would not run at once, because the generator stays paused at its yield. Python's event loop schedules cleanup of abandoned async generators later, at garbage collection or shutdown, so the timing is not reliable. Calling aclose() runs the finally block immediately and predictably.