Asynchronous generators

suggest change

An asynchronous generator is a function defined with async def that contains yield. It combines two ideas:

You consume it with async for instead of for. Async generators are the natural way to model a stream of data that arrives over time: pages from an HTTP API, rows from an async database driver, lines from a subprocess, messages from a websocket.

They were added in Python 3.6 (PEP 525), along with async comprehensions (PEP 530). All examples here run on Python 3.10+; a few use features from 3.11 and 3.13, which is noted.

A first async generator

import asyncio


async def ticker(count, delay):
    for i in range(count):
        await asyncio.sleep(delay)   # wait without blocking the event loop
        yield i


async def main():
    async for n in ticker(3, 0.1):
        print("tick", n)


asyncio.run(main())
tick 0
tick 1
tick 2

Each iteration of async for resumes the generator, which runs until the next yield. While it's sleeping in await asyncio.sleep(), other tasks on the event loop are free to run.

The difference from a normal generator is easiest to see when two of them run at the same time:

import asyncio
import time


async def ticker(name, count, delay):
    for i in range(count):
        await asyncio.sleep(delay)
        yield f"{name}{i}"


async def consume(name):
    async for value in ticker(name, 3, 0.1):
        print(value, end=" ")


async def main():
    start = time.perf_counter()
    await asyncio.gather(consume("a"), consume("b"))
    print(f"\ntook {time.perf_counter() - start:.1f}s")


asyncio.run(main())
a0 b0 a1 b1 a2 b2 
took 0.3s

Six values, each taking 0.1 s, finish in 0.3 s because the two streams are interleaved on a single thread.

What an async generator really is

Calling an async generator function doesn't run any of its code. It returns an async generator object, which implements the asynchronous iterator protocol: __aiter__() returns itself and __anext__() returns an awaitable that produces the next value.

import asyncio


async def numbers():
    print("started")
    yield 1
    yield 2


async def main():
    gen = numbers()
    print(type(gen).__name__)
    print(gen.__aiter__() is gen)

    print(await anext(gen))      # anext() is a built-in since 3.10
    print(await anext(gen))
    print(await anext(gen, "done"))  # default instead of StopAsyncIteration

    try:
        await anext(gen)
    except StopAsyncIteration:
        print("exhausted")


asyncio.run(main())
async_generator
True
started
1
2
done
exhausted

The built-ins aiter() and anext() are the async counterparts of iter() and next(). When an async iterator is exhausted, __anext__() raises StopAsyncIteration (not StopIteration), and async for treats that as the end of the loop.

You can't use a plain for loop on an async generator, and you can't await the generator object itself:

import asyncio


async def numbers():
    yield 1


async def main():
    try:
        for n in numbers():
            pass
    except TypeError as e:
        print("TypeError:", e)


asyncio.run(main())
TypeError: 'async_generator' object is not iterable

Async comprehensions

Inside an async def function you can use async for in list, set and dict comprehensions and in generator expressions. You can also await inside a comprehension:

import asyncio


async def ticker(count):
    for i in range(count):
        await asyncio.sleep(0)
        yield i


async def square(x):
    await asyncio.sleep(0)
    return x * x


async def main():
    evens = [n async for n in ticker(10) if n % 2 == 0]
    print(evens)

    squares = {n: await square(n) async for n in ticker(4)}
    print(squares)

    # an async generator expression: lazy, produces an async generator
    doubled = (n * 2 async for n in ticker(3))
    print(type(doubled).__name__)
    print([x async for x in doubled])


asyncio.run(main())
[0, 2, 4, 6, 8]
{0: 0, 1: 1, 2: 4, 3: 9}
async_generator
[0, 2, 4]

Restrictions compared to regular generators

Async generators have two syntax restrictions.

No yield from. To delegate to another async generator, loop over it explicitly:

import asyncio


async def letters():
    for ch in "ab":
        await asyncio.sleep(0)
        yield ch


async def numbers():
    for n in (1, 2):
        await asyncio.sleep(0)
        yield n


async def combined():
    # 'yield from letters()' is a SyntaxError inside 'async def'
    async for x in letters():
        yield x
    async for x in numbers():
        yield x


async def main():
    print([x async for x in combined()])


asyncio.run(main())
['a', 'b', 1, 2]

No return value. A bare return is fine and ends the generator, but return 42 is a SyntaxError ("'return' with value in async generator"). If you need a final result, yield it or store it on an object.

Cleanup with try/finally

Async generators often own resources such as a connection or a file. Put the cleanup in a finally block; since cleanup is itself often async, you can await inside finally:

import asyncio


async def read_rows():
    print("open connection")
    try:
        for i in range(1, 4):
            await asyncio.sleep(0)
            yield {"id": i}
    finally:
        await asyncio.sleep(0)       # e.g. await conn.close()
        print("close connection")


async def main():
    async for row in read_rows():
        print(row)


asyncio.run(main())
open connection
{'id': 1}
{'id': 2}
{'id': 3}
close connection

When the generator runs to completion, the finally runs right away. The tricky case is when the consumer stops early.

Breaking out of the loop early

With a synchronous generator, break drops the last reference and CPython closes the generator immediately. An async generator can't be closed synchronously, because its finally block may need to await. Instead, the event loop schedules aclose() later, when the generator is garbage collected, or at the very latest when asyncio.run() shuts down:

import asyncio


async def read_rows():
    print("open connection")
    try:
        for i in range(1, 100):
            await asyncio.sleep(0)
            yield {"id": i}
    finally:
        print("close connection")


async def main():
    rows = read_rows()
    async for row in rows:
        print(row)
        if row["id"] == 2:
            break
    print("after loop")
    await asyncio.sleep(0.1)
    print("end of main")


asyncio.run(main())
open connection
{'id': 1}
{'id': 2}
after loop
end of main
close connection

The connection stays open until asyncio.run() finalizes leftover async generators. In a long-running server that may be much later than you'd like. The fix is to close the generator explicitly with await gen.aclose(), or more conveniently with contextlib.aclosing() (Python 3.10+):

import asyncio
from contextlib import aclosing


async def read_rows():
    print("open connection")
    try:
        for i in range(1, 100):
            await asyncio.sleep(0)
            yield {"id": i}
    finally:
        print("close connection")


async def main():
    async with aclosing(read_rows()) as rows:
        async for row in rows:
            print(row)
            if row["id"] == 2:
                break
    print("after loop")


asyncio.run(main())
open connection
{'id': 1}
{'id': 2}
close connection
after loop

aclosing() calls aclose() when the async with block exits, whether by break, return or an exception. Use it whenever an async generator holds a resource and the consumer might not exhaust it.

aclose() works by raising GeneratorExit at the paused yield. Don't catch GeneratorExit and then yield again; that raises RuntimeError: async generator ignored GeneratorExit.

asend() and athrow()

Async generators mirror the send() and throw() methods of regular generators (see Sending objects to a generator) as awaitable methods asend() and athrow():

import asyncio


async def running_average():
    total = 0
    count = 0
    average = None
    while True:
        try:
            value = yield average
        except ValueError:
            print("reset")
            total = count = 0
            average = None
            continue
        total += value
        count += 1
        average = total / count


async def main():
    avg = running_average()
    await avg.asend(None)          # prime it: run to the first yield
    print(await avg.asend(10))
    print(await avg.asend(20))
    print(await avg.athrow(ValueError))
    print(await avg.asend(5))
    await avg.aclose()


asyncio.run(main())
10.0
15.0
reset
None
5.0

In practice these are rarely used; async generators are almost always consumed with async for.

Practical example: paginated API

A very common use is hiding pagination. The consumer sees a flat stream of items, and pages are fetched only as needed:

import asyncio

FAKE_DB = [f"item-{i}" for i in range(7)]


async def fetch_page(cursor, size=3):
    """Pretend to be an HTTP call: returns (items, next_cursor)."""
    await asyncio.sleep(0.05)
    print(f"  fetched page at cursor {cursor}")
    items = FAKE_DB[cursor:cursor + size]
    next_cursor = cursor + size if cursor + size < len(FAKE_DB) else None
    return items, next_cursor


async def all_items():
    cursor = 0
    while cursor is not None:
        items, cursor = await fetch_page(cursor)
        for item in items:
            yield item


async def main():
    async for item in all_items():
        print(item)
        if item == "item-4":
            break     # page 3 is never fetched


asyncio.run(main())
  fetched page at cursor 0
item-0
item-1
item-2
  fetched page at cursor 3
item-3
item-4

With a real HTTP client such as httpx.AsyncClient or aiohttp, fetch_page would await client.get(...) and the rest stays the same.

Building pipelines

Async generators compose like Unix pipes: each stage takes an async iterable and yields transformed values. Nothing runs until the final consumer pulls data.

import asyncio
from collections.abc import AsyncIterable, AsyncIterator


async def source(n: int) -> AsyncIterator[int]:
    for i in range(n):
        await asyncio.sleep(0.01)
        yield i


async def only_odd(items: AsyncIterable[int]) -> AsyncIterator[int]:
    async for x in items:
        if x % 2:
            yield x


async def batched(items: AsyncIterable[int], size: int) -> AsyncIterator[list[int]]:
    batch = []
    async for x in items:
        batch.append(x)
        if len(batch) == size:
            yield batch
            batch = []
    if batch:
        yield batch


async def main():
    async for batch in batched(only_odd(source(12)), 2):
        print(batch)


asyncio.run(main())
[1, 3]
[5, 7]
[9, 11]

Timeouts

You can wrap an await anext(...) in a timeout to stop waiting for a slow stream. asyncio.timeout() is available since Python 3.11:

import asyncio
from contextlib import aclosing


async def sensor():
    delays = [0.05, 0.05, 0.5, 0.05]
    for i, d in enumerate(delays):
        await asyncio.sleep(d)
        yield i


async def main():
    async with aclosing(sensor()) as readings:
        while True:
            try:
                async with asyncio.timeout(0.2):
                    value = await anext(readings)
            except TimeoutError:
                print("sensor too slow, giving up")
                break
            except StopAsyncIteration:
                break
            print("reading", value)


asyncio.run(main())
reading 0
reading 1
sensor too slow, giving up

Note that the timeout cancels the generator while it is suspended at an await, so the generator is finished after that; you can't keep pulling values from it. Close it (here, via aclosing) and move on.

If you want a timeout for the whole loop instead of each item, put async with asyncio.timeout(...) around the async for.

Merging several streams

async for consumes one stream at a time. To merge several async generators and get values in the order they arrive, run each in its own task and feed a queue:

import asyncio
from collections.abc import AsyncIterator

_DONE = object()


async def ticker(name, count, delay):
    for i in range(count):
        await asyncio.sleep(delay)
        yield f"{name}{i}"


async def merge(*streams: AsyncIterator) -> AsyncIterator:
    queue = asyncio.Queue()

    async def drain(stream):
        async for item in stream:
            await queue.put(item)
        await queue.put(_DONE)

    async with asyncio.TaskGroup() as tg:     # Python 3.11+
        for s in streams:
            tg.create_task(drain(s))
        remaining = len(streams)
        while remaining:
            item = await queue.get()
            if item is _DONE:
                remaining -= 1
            else:
                yield item


async def main():
    fast = ticker("fast", 4, 0.05)
    slow = ticker("slow", 2, 0.12)
    async for item in merge(fast, slow):
        print(item)


asyncio.run(main())
fast0
fast1
slow0
fast2
fast3
slow1

This version is fine when the consumer reads every value. Libraries such as aiostream (stream.merge) offer a more complete implementation that also handles early exit and cancellation of the producer tasks.

Async context managers from generators

contextlib.asynccontextmanager turns an async generator that yields exactly once into an async context manager, the async version of @contextmanager:

import asyncio
from contextlib import asynccontextmanager


@asynccontextmanager
async def connection(name):
    await asyncio.sleep(0)            # e.g. await connect()
    print(f"connected to {name}")
    try:
        yield f"<conn {name}>"
    finally:
        await asyncio.sleep(0)        # e.g. await conn.close()
        print(f"disconnected from {name}")


async def main():
    async with connection("db") as conn:
        print("using", conn)


asyncio.run(main())
connected to db
using <conn db>
disconnected from db

Type hints

Annotate an async generator function with AsyncIterator[T] if callers only iterate over it, or AsyncGenerator[YieldType, SendType] if you use asend(). Import them from collections.abc:

from collections.abc import AsyncGenerator, AsyncIterator


async def countdown(n: int) -> AsyncIterator[int]:
    while n > 0:
        yield n
        n -= 1


async def echo() -> AsyncGenerator[str, str]:
    received = yield "ready"
    while True:
        received = yield f"echo: {received}"

Since Python 3.13 the send type has a default of None, so AsyncGenerator[int] means AsyncGenerator[int, None]. Unlike Generator, there's no return type parameter, because async generators can't return a value.

Functions that accept a stream should take AsyncIterable[T] so they work with any object that has __aiter__, not just async generators.

Writing an async iterator class

An async generator is a shortcut for a class that implements __aiter__ and __anext__. Writing the class by hand is occasionally useful when the iterator needs extra methods or state that callers can inspect:

import asyncio


class Countdown:
    def __init__(self, start):
        self.current = start

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.current <= 0:
            raise StopAsyncIteration
        await asyncio.sleep(0)
        value = self.current
        self.current -= 1
        return value


async def countdown(start):          # the same thing as an async generator
    while start > 0:
        await asyncio.sleep(0)
        yield start
        start -= 1


async def main():
    print([n async for n in Countdown(3)])
    print([n async for n in countdown(3)])


asyncio.run(main())
[3, 2, 1]
[3, 2, 1]

Note that __aiter__ is a regular method (not async def) and must return the async iterator directly.

Common pitfalls

Consuming one generator from two tasks at once. An async generator can only be advanced by one caller at a time:

import asyncio


async def slow_numbers():
    for i in range(3):
        await asyncio.sleep(0.1)
        yield i


async def main():
    gen = slow_numbers()
    try:
        await asyncio.gather(anext(gen), anext(gen))
    except RuntimeError as e:
        print("RuntimeError:", e)


asyncio.run(main())
RuntimeError: anext(): asynchronous generator is already running

To share a stream between several workers, have one task read from the generator and put items into an asyncio.Queue that the workers read from.

Blocking calls inside the generator. async def doesn't make code non-blocking. A time.sleep(), requests.get() or heavy computation inside an async generator freezes the whole event loop. Use async libraries, or push blocking work to a thread with await asyncio.to_thread(func, *args) (see Asynchronous Executors).

Forgetting to close. If the consumer may stop early and the generator holds a resource, wrap it in contextlib.aclosing(). Relying on garbage collection means cleanup happens at an unpredictable time, and an await in the finally block can fail if the event loop is already gone.

Turning a stream into a list too eagerly. [x async for x in gen] loads everything into memory and waits for the last item. That's fine for small results, but the point of an async generator is usually to process items as they arrive.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents