Python Glossary Русский

Python 3.4+Async programmingfunction

asyncio.as_completed()

concurrency

Yields the results of a set of awaitables as they complete, not in the order they were passed; an overall timeout can be set.

Syntax

for coro in asyncio.as_completed(aws, *, timeout=None): result = await coro

Before 3.13 it is a plain iterator yielding fresh coroutines, not your tasks: for c in as_completed(aws): r = await c — so you can match a result to its task only through the result itself. Since 3.13 async for also works and yields the original tasks. The timeout covers the whole loop: once it expires the next await raises TimeoutError, and unfinished tasks are not cancelled — cancel them yourself.

Examples

import asyncio
async def fetch(name, delay):
    await asyncio.sleep(delay)
    return name
async def main():
    aws = [fetch('медленный', 0.03), fetch('быстрый', 0.01)]
    for coro in asyncio.as_completed(aws):
        print(await coro)  # → быстрый / медленный
asyncio.run(main())
# Python 3.13+
import asyncio
async def fetch(delay):
    await asyncio.sleep(delay)
    return delay
async def main():
    tasks = [asyncio.create_task(fetch(d)) for d in (0.02, 0.01)]
    async for task in asyncio.as_completed(tasks):
        print(task is tasks[1], task.result())  # → True 0.01 / False 0.02
asyncio.run(main())

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy