Sub topic 14
Async iterators, context managers, and generators
This chapter assumes you know Python generators, iterators, and context managers, and that you can write coroutines with async def and await. It shows how those three features work when the code needs to await in the middle of them.
Why async versions exist
A normal for loop calls __next__, and a normal with block calls __enter__ and __exit__. All of these are plain functions. They cannot await, so they would block the event loop if they had to wait for a network read or a connection to close.
Python adds async versions of each feature. Their methods are coroutines, so they can suspend while the event loop runs other tasks.
| Synchronous | Asynchronous | Methods involved |
|---|---|---|
| `for` | `async for` | `__aiter__`, `__anext__` |
| `with` | `async with` | `__aenter__`, `__aexit__` |
| generator (`yield` in `def`) | async generator (`yield` in `async def`) | `__aiter__`, `__anext__` |
You can use async for and async with only inside an async def function.
Async generators
The simplest way to make an async iterator is an async generator. Write yield inside an async def. The generator 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, with a short pause after each value. While the generator sleeps, the event loop is free to run other tasks.
Two details matter:
- An async generator function cannot use
returnwith a value. A barereturnends the iteration. - Calling
countdown(3)does not run any code. It returns an async generator object, and the body runs asasync forasks for each value.
Async iterators as classes
When you need more control, write a class with __aiter__ and __anext__. __aiter__ is a normal method that returns the iterator. __anext__ is a coroutine that returns the next value or raises StopAsyncIteration when there are no more values.
import asyncio
class Ticker:
def __init__(self, count):
self.count = count
self.current = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.current >= self.count:
raise StopAsyncIteration
self.current += 1
await asyncio.sleep(0.1)
return self.current
async def main():
async for tick in Ticker(3):
print("tick", tick)
asyncio.run(main())Async context managers
An async context manager does setup and cleanup that may need to await, such as opening and closing a connection. You can write one with __aenter__ and __aexit__, or use the contextlib.asynccontextmanager decorator on an async generator.
import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def connection(name):
print("open", name)
await asyncio.sleep(0.1)
try:
yield name
finally:
await asyncio.sleep(0.1)
print("close", name)
async def main():
async with connection("db") as conn:
print("using", conn)
asyncio.run(main())The finally block runs even if the body raises an exception or the task is cancelled. Put cleanup there. You have already seen this feature in use: asyncio.timeout() and asyncio.TaskGroup() are both async context managers.
Common mistakes
- Using
foron an async iterator raisesTypeError. Useasync for. - Using plain
withon an async context manager fails the same way. Useasync with. - Abandoning an async generator before it finishes delays its cleanup. If you may stop early with
break, wrap the generator incontextlib.aclosingso it is closed right away.
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():
async with aclosing(numbers()) as gen:
async for n in gen:
if n == 2:
break
asyncio.run(main())Exercise
Why does async for fail with a TypeError when you use it on an ordinary list-returning function's result inside a coroutine, and what keyword do you use to loop over a list in the same coroutine?
Show answer
A list has __iter__ but no __aiter__, so async for cannot use it. Loop over a list with a regular for, even inside an async def function.
Exercise
In the connection example, what happens to the "close" message if the body of the async with block raises an exception?
Show answer
The "close" message still prints, because the cleanup code is in a finally block, which runs whether the body finishes normally, raises, or is cancelled.