Python Glossary Русский

Python 3.5+Async programmingterm

async for / async with

iteration

async for iterates over an asynchronous iterator. async with uses an asynchronous context manager.

Syntax

async for item in aiter: ...
async with ctx_manager() as obj: ...

Neither form makes anything parallel: async for still walks items one at a time, it just yields control back to the event loop between steps. Both are allowed only inside an async def, and only for objects implementing __aiter__/__anext__ (or __aenter__/__aexit__) — a plain list or a sync context manager raises TypeError. When you actually want things to overlap, collect the coroutines and hand them to gather or a TaskGroup.

Examples

import asyncio
async def agen():
    for i in range(3):
        await asyncio.sleep(0)
        yield i
async def main():
    async for val in agen():
        print(val)  # → 0 / 1 / 2
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy