Python Glossary Русский

Python 3.6+Iterators & generatorsconstruct

Asynchronous generator

generators

An async def function containing yield: it produces values one by one and may await between them. It is consumed with async for.

Syntax

async def имя(...):
    yield значение

async for x in имя(...): ...

The main trap: a plain for cannot iterate such an object — you get TypeError; use async for or [x async for x in ...] inside a coroutine. Unlike a regular generator, yield from and return with a value are not allowed inside — that is a SyntaxError. Pick an async generator when you need to await I/O between values; if there is nothing to await, a regular generator is enough.

Examples

import asyncio
async def countdown(n):
    while n > 0:
        yield n
        await asyncio.sleep(0)
        n -= 1
async def main():
    async for i in countdown(3):
        print(i)  # → 3 / 2 / 1
    print([i async for i in countdown(2)])  # → [2, 1]
asyncio.run(main())
async def agen():
    yield 1
print(type(agen()).__name__)  # → async_generator
for x in agen():  # → TypeError
    pass

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy