Question presented to candidate:
"You already know how a normal for loop works over an iterator. What changes when the next item has to come from the network? Explain what an async iterator is, what async for actually does, and how you would write one."
What a strong answer should cover:
- The protocol:
__aiter__(a plain method that returns the async iterator) and__anext__(returns an awaitable, usually anasync def), ending withStopAsyncIterationinstead ofStopIteration. async foris only legal insideasync def; each step awaits__anext__(), so the event loop can run other tasks while the next item is being fetched.- The easy way to write one is an async generator (
async def+yield, PEP 525, Python 3.6); it getsasend,athrowandaclosefor free and cannotreturna value. - The helpers:
aiter()/anext()builtins (3.10), async comprehensions[x async for x in src](PEP 530). - Early exit: after
break, an async generator is left suspended and asyncio closes it later;contextlib.aclosing(orawait gen.aclose()) makes the cleanup happen at a known point. - The common errors:
async forover a list and a plainforover an async generator are bothTypeErrors.
Code / implementation expected: Optional โ a small class with __aiter__ / __anext__ or an async generator consumed with async for.