Lesson · Async Python
Async Context Managers & Iterators
81 min readAsync Context Managers & Iterators
Async context managers and async iterators extend familiar `with` and `for` protocols across suspension points. They are essential for streaming resources such as network connections and asynchronous data sources.
Learning goals
- Read a class and tell which of the four async protocol methods it defines and what each must return.
- Explain why
async forcalls__anext__one extra time and howStopAsyncIterationends the loop. - Trace
AsyncCounter(3)producing 1, 2, 3 and point to the guard that stops it. - Contrast an async context manager with a plain one and say why acquisition sometimes needs to await.
- Decide when an async generator replaces the full iterator protocol with less code.
Mental model
Both protocols mirror a synchronous one, with the difference that setup, each item, and teardown are awaited, so the loop can run other work while a resource is acquired or read. The right column is the whole iterator contract: __aiter__ returns an object with an async __anext__, and the loop stops at StopAsyncIteration.
Mental model
read it top to bottom
async with: __aenter__ (await) → body → __aexit__ (await) async for: __aiter__ → __anext__ (await), repeated → StopAsyncIteration ends
Core idea
async with and async for extend the familiar with and for protocols across awaits: __aenter__ and __aexit__ may suspend while a resource is acquired or released, and __anext__ may suspend while the next item is produced. The AsyncCounter example shows the iterator half in full: one object serves as both iterable and iterator, self.current carries state, and the guard that raises StopAsyncIteration is the normal way the loop ends.
async with
async with runs its body only after awaiting the manager's __aenter__, and it guarantees an awaited call to __aexit__ on the way out, including when the body raises. Reach for it whenever acquiring or releasing the resource itself needs to wait, such as opening a network connection or a database cursor.
__aenter__
__aenter__ is the coroutine async with awaits before entering the body. Its return value is what the as target binds, so a manager can hand the body a ready connection, a lock owner, or any prepared object.
__aexit__
__aexit__ is the coroutine async with awaits when the block ends, receiving the exception details if the body failed. A falsy return lets the exception propagate and a true return suppresses it, so ordinary cleanup releases the resource and returns None.
async for
async for repeatedly awaits the iterator's __anext__ and binds each returned value until StopAsyncIteration ends the loop. The loop can suspend between iterations, which lets other tasks run while the next item is being produced.
__aiter__
__aiter__ is called once by async for and must return an object with an async __anext__. Returning self is the common choice when the same object is both iterable and iterator, as AsyncCounter does.
__anext__
__anext__ is a coroutine that returns the next value or raises StopAsyncIteration when the sequence is exhausted. It may await on the way, which is what separates it from the synchronous __next__ and why the enclosing loop has to be async for.
Async generator functions
An async generator function is declared with async def and contains yield; calling it returns an async generator that async for can consume. Values appear one await at a time, and the generator is exhausted when the function falls off the end or returns.
async for over async generators
Iterating an async generator with async for drives its awaits and yields interleaved with the rest of the loop. Each yield suspends the generator, so local state survives between items exactly as in a synchronous generator, and the loop needs no protocol methods of its own.
Async-generator cleanup
Async generators release resources when they are closed: aclose() throws GeneratorExit at the current yield, so finally blocks run. Letting garbage collection trigger that asynchronously is harder to reason about, so close a generator deliberately when its lifetime matters, or wrap it in a manager that does.
Walkthrough
AsyncCounter(3)builds one object that plays both roles:__aiter__returnsself, andself.currentcarries the count between iterations.- Each trip through
async forawaits__anext__; the guardif self.current >= self.limitraisesStopAsyncIterationonce three values have been produced, which ends the loop rather than acting as an error. await asyncio.sleep(0)is the suspension point inside__anext__: it yields to the loop with no real delay, thenself.current += 1runs and the value is returned, so the output is 1, 2, 3.- Predict before running: how many times
__anext__is called forlimit=3(four, counting the finalStopAsyncIteration) and what prints forlimit=0.
Experiments to try
- Set
limit = 0, thenlimit = 1, and count the printed values; explain the zero case from the guard in__anext__. - Print inside
__anext__before and after the sleep; confirmasync forawaits it once per value plus one final call, four in total for three values. - Replace
await asyncio.sleep(0)withawait asyncio.sleep(0.05)and time the run; the total should reflect a wait per item. - Rewrite the class as an async generator (
async def count(limit)withyield) and swap it into the sameasync for; compare the line count of the two versions.
Common mistakes
- Using a plain
fororwithon an async object: the synchronous protocols are not defined, so Python raisesTypeErrorand points at the loop statement rather than the object's methods. - Omitting
raise StopAsyncIterationin__anext__: nothing else signals the end, so the loop keeps awaiting values forever. - Defining
__aenter__or__aexit__as regulardeffunctions:async withawaits whatever they return, and a non-awaitable result fails with aTypeErrorat the statement. - Leaving an async generator half-consumed: resources held in its
finallyblocks survive untilaclose()runs, which garbage collection only schedules asynchronously.
Practice: Easy
- Run the worked example and print
counter.currentinside the loop as well as the loop value; verify the sequence 1, 2, 3 and where the loop stops. - Change
limitto 0 and to 1 and write the expected number of printed lines for each before running. - Swap
await asyncio.sleep(0)forawait asyncio.sleep(0.05)and time the run withtime.perf_counter(); state what the total says about waiting per item.
Practice: Medium
- Rewrite
AsyncCounteras an async generator functioncount(limit)and drive it with the sameasync for; note which protocol methods disappeared. - Build an
AsyncResourcemanager whose__aenter__returnsselfand whose__aexit__prints "closed"; use it withasync with, raise inside the body, and confirm__aexit__still runs. - Iterate two separate
AsyncCounterinstances inside two consumer coroutines gathered together and record the interleaved output order.
Practice: Hard
- Connect a producer to an async generator: put 1 to 5 into an
asyncio.Queue, read it withasync forin a consumer, close the generator withaclose(), and state when itsfinallyblock runs. - Make
__aexit__return True, raise inside the body, and show the exception is suppressed; then return None and show it propagates; explain the boolean's role in the protocol. - Convert the protocol class into an async generator and compare both on line count, where state lives, and what a
breakmeans for cleanup in each version.
Lesson checklist
- I can name the four protocol methods the two async statements rely on and what each returns.
- I can explain why
__anext__raisingStopAsyncIterationis the normal end of the loop. - I can make a class work with
async forwhere__aiter__returnsself. - I can say what
__aexit__'s return value does to an exception raised in the body.
Remember
`async with` and `async for` are the familiar `with` and `for` protocols with awaits at acquisition, per item, and release. `__aenter__` prepares and `__aexit__` cleans up, `__aiter__` hands out an iterator whose `__anext__` awaits values until `StopAsyncIteration`, and an async generator packages the iterator half into one function with `yield`.
Interview angles
What is the main purpose of **async with**?+
async with runs its body only after awaiting the manager's __aenter__, and it guarantees an awaited call to __aexit__ on the way out, including when the body raises. Reach for it whenever acquiring or releasing the resource itself needs to wait, such as opening a network connection or a database cursor.
What should you pay attention to when using **__aenter__**?+
__aenter__ is the coroutine async with awaits before entering the body. Its return value is what the as target binds, so a manager can hand the body a ready connection, a lock owner, or any prepared object.
How does **__aexit__** fit into this lesson?+
__aexit__ is the coroutine async with awaits when the block ends, receiving the exception details if the body failed. A falsy return lets the exception propagate and a true return suppresses it, so ordinary cleanup releases the resource and returns None.
What happens when `__anext__` never raises `StopAsyncIteration`?+
The loop never ends: async for treats only that exception as completion, so it keeps awaiting the next value. A missing guard turns a finite source into an infinite loop that also never lets the enclosing task finish.