Sub topic 14
Async iterators, context managers, and generators
This chapter assumes you know ordinary generators and iterators, with statements and context managers, and the basics of coroutines and await from earlier chapters. Here you will see how the three protocols you already know get asynchronous versions. These are async for, async with, and async def functions that contain yield.
Why synchronous protocols are not enough
A normal for loop calls __next__, and a normal with block calls __enter__ and __exit__. All three are plain methods. They cannot suspend, so if getting the next item means waiting on a network read, the whole thread blocks and the event loop stalls.
The asynchronous versions make those steps awaitable. While one task waits for its next item or its cleanup, the loop runs other tasks.
| Synchronous | Asynchronous | Methods |
|---|---|---|
| `for` | `async for` | `__aiter__`, `__anext__` |
| `with` | `async with` | `__aenter__`, `__aexit__` |
| generator function | async generator function | `yield` inside `async def` |
| list comprehension | async comprehension | `[x async for x in source]` |
async for and async with are only legal inside an async def function. Using them anywhere else is a SyntaxError.
Async generators
The simplest way to write an async iterator is an async generator: an async def function whose body contains yield. It can await between values.
import asyncio
async def countdown(n):
while n > 0:
yield n
await asyncio.sleep(0.1)
n -= 1
async def main():
async for value in countdown(3):
print(value)
asyncio.run(main())This prints 3, 2, 1. Calling countdown(3) does not run any of the body. It returns an async generator object, and the body runs as async for asks for each value.
Some rules and edge cases:
- An async generator cannot use
return value. A barereturnis allowed and ends the iteration. - A plain
forloop over an async generator fails withTypeError, because the object has no__iter__. - Awaiting the generator object, as in
await countdown(3), also fails. You iterate it. You do not await it. - Each
yieldis a suspension point for the consumer. The generator body runs only while the consumer is waiting for the next value.
How `async for` drives the loop
When the generator finishes, __anext__ raises StopAsyncIteration. The async for statement catches it and leaves the loop, the same way for handles StopIteration.
Writing an async iterator as a class
Use a class when the iterator carries state you want to expose, or when you need more control than a generator gives you. The class must provide __aiter__, which returns the iterator and is usually a plain method, and __anext__, which is a coroutine.
import asyncio
class Ticker:
def __init__(self, count, delay):
self.count = count
self.delay = delay
self.current = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.current >= self.count:
raise StopAsyncIteration
await asyncio.sleep(self.delay)
self.current += 1
return self.current
async def main():
async for n in Ticker(3, 0.1):
print(n)
asyncio.run(main())A common mistake is declaring __anext__ without async. The loop awaits the return value, so a plain method returning an integer produces a TypeError about awaiting an int.
Async context managers
An async context manager defines __aenter__ and __aexit__, both coroutines. Use one when setting up or tearing down a resource needs I/O, such as opening a connection or flushing a buffer to the network.
import asyncio
class Connection:
async def __aenter__(self):
await asyncio.sleep(0.1)
print("opened")
return self
async def __aexit__(self, exc_type, exc, tb):
await asyncio.sleep(0.1)
print("closed")
return False
async def query(self, sql):
await asyncio.sleep(0.1)
return f"result of {sql}"
async def main():
async with Connection() as conn:
print(await conn.query("SELECT 1"))
asyncio.run(main())The output is opened, then the query result, then closed. __aexit__ receives the exception details if the block raised. Returning a true value suppresses the exception, so returning False (or None) lets it propagate. Suppress errors only on purpose.
You have already used async context managers in this tutorial. asyncio.TaskGroup, asyncio.timeout, and asyncio.Semaphore all work with async with.
The decorator shortcut
Writing a class for every resource is verbose. The contextlib.asynccontextmanager decorator turns an async generator with exactly one yield into an async context manager.
import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def connect(name):
await asyncio.sleep(0.1)
print("connected to", name)
try:
yield name.upper()
finally:
await asyncio.sleep(0.1)
print("disconnected from", name)
async def main():
async with connect("db") as conn:
print("using", conn)
raise RuntimeError("query failed")
try:
asyncio.run(main())
except RuntimeError as exc:
print("caught:", exc)Code before yield is the setup. The yielded value is what as binds. Code after yield is the teardown. Because an exception in the async with body is re-raised at the yield, you must wrap it in try/finally if the teardown has to run on errors. Here the output shows disconnected from db before caught: query failed.
You can combine several managers in one statement, for example async with a() as x, b() as y:. They are entered left to right and exited in reverse order.
Async comprehensions and cleanup
Comprehensions accept async for too. They must also appear inside an async def.
import asyncio
from contextlib import aclosing
async def numbers():
try:
for i in range(10):
yield i
await asyncio.sleep(0)
finally:
print("generator closed")
async def main():
squares = [n * n async for n in numbers() if n % 2 == 0]
print(squares)
async with aclosing(numbers()) as gen:
async for n in gen:
if n == 2:
break
print("after break")
asyncio.run(main())The first comprehension consumes the generator to the end, so its finally block runs on its own. The second loop stops early with break. That leaves the generator suspended at a yield, and nothing guarantees when its cleanup runs. Without aclosing, the interpreter finalizes the generator later through the event loop's asynchronous-generator hooks. Cleanup then happens at an unpredictable moment, and may happen after the loop has shut down.
contextlib.aclosing (Python 3.10 and later) calls aclose() when the block exits. That throws GeneratorExit into the generator at its yield, so its finally runs immediately. Use it whenever an async generator holds a resource and you might not exhaust it.
Gotchas
- Do not
awaitinside afinallyafter cancellation unless you mean to. If the consuming task is cancelled, the generator's cleanup may itself be cancelled partway through. - Do not
yieldinside aTaskGrouportimeoutblock in a generator. The block's scope then spans the consumer's code, and cancellation can be delivered at confusing points. Collect the results first, or use a queue. - One consumer at a time. Two tasks calling
__anext__on the same async generator concurrently raiseRuntimeError. Share a generator through a queue instead. - Use
anextfor single items. The built-inanext(gen)(Python 3.10 and later) returns an awaitable for the next value, so you can writeawait asyncio.wait_for(anext(gen), 1)to put a timeout on one item.
Choosing the right tool
| Situation | Use |
|---|---|
| Produce a stream of values with awaits between them | Async generator |
| Iterator needs public state or several methods | Class with `__aiter__` and `__anext__` |
| Resource with async setup and teardown | `async with` and a class or `@asynccontextmanager` |
| Generator may be abandoned early | Wrap it in `aclosing` |
| Many consumers need the same stream | Feed an `asyncio.Queue` |
Exercise
An async generator opens a file handle in a try block and closes it in finally. A consumer reads two items with async for and then breaks out of the loop. Why might the file stay open, and how do you make the close happen immediately?
Show answer
Breaking out of the loop leaves the generator suspended at its yield, so its finally block does not run until the interpreter finalizes the generator later. Wrap the generator in contextlib.aclosing, as in "async with aclosing(gen()) as g: async for item in g: ...". When the block exits, aclose() throws GeneratorExit into the generator and the finally block runs right away.
Exercise
You write "async def _anext(self)" correctly but forget to define aiter on your class, then use "async for x in Obj():". What error do you get, and what is the usual body of aiter_?
Show answer
You get a TypeError saying the object is not an async iterable, because async for first needs _aiter. For an iterator class, aiter_ is a normal method that returns self.