APIs and Async · Async Python · lesson 8 of 12
Async iteration
about 16 minutes · free · runs in your browser
Streaming results as they arrive
Sometimes you cannot fetch everything up front — the pages are unbounded, or you want to
start work on the first result before the last arrives. That is what async for is
for.
An async iterator defines __aiter__ and __anext__, and signals the end by raising
StopAsyncIteration:
class Pages:
def __init__(self, last):
self.page = 0
self.last = last
def __aiter__(self):
return self
async def __anext__(self):
if self.page >= self.last:
raise StopAsyncIteration
self.page += 1
await asyncio.sleep(0)
return self.page
async def main():
async for page in Pages(3):
print(page)
An async generator is the shorter way to write the same thing — an async def with
yield in it:
async def pages(last):
for n in range(1, last + 1):
await asyncio.sleep(0)
yield n
Your turn: write an async generator countdown(n) yielding n down to 1, and
collect(n) that gathers its values into a list with async for.
You start from this, and edit it in the browser:
import asyncio
async def countdown(n):
# An async generator yielding n down to 1.
pass
async def collect(n):
# Consume countdown(n) with an `async for` loop and return a list.
pass