Skip to the solution
HardDSA15 min read

What is an async iterator and async for?

954 views

The problem

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 an async def), ending with StopAsyncIteration instead of StopIteration.
  • async for is only legal inside async 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 gets asend, athrow and aclose for free and cannot return a 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 (or await gen.aclose()) makes the cleanup happen at a known point.
  • The common errors: async for over a list and a plain for over an async generator are both TypeErrors.

Code / implementation expected: Optional โ€” a small class with __aiter__ / __anext__ or an async generator consumed with async for.

  • async
  • async-iterator

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read ยท 13 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonStreaming pages and rows with async for, on a fake clock
Pythonaiter, anext, aclose, the two TypeErrors, and break cleanup

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 119 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextHard

What is a metaclass?

Continue