Python Glossary Русский

Python 3.4+Async programmingfunction

asyncio.wait()

concurrency

Waits for a set of tasks and returns two sets, done and pending; return_when sets the stopping condition.

Syntax

done, pending = await asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED)

Unlike gather and wait_for, wait() neither raises nor cancels: exceptions stay inside the tasks (fetch them with task.result() or task.exception()), and pending tasks keep running after the timeout. Since 3.11 bare coroutines are rejected with TypeError; pass tasks from create_task. FIRST_COMPLETED suits "whoever is first", FIRST_EXCEPTION stops on the first failure.

Examples

import asyncio
async def main():
    fast = asyncio.create_task(asyncio.sleep(0.01, result='быстрый'))
    slow = asyncio.create_task(asyncio.sleep(1, result='медленный'))
    done, pending = await asyncio.wait({fast, slow}, return_when=asyncio.FIRST_COMPLETED)
    print([t.result() for t in done], len(pending))  # → ['быстрый'] 1
    for t in pending:
        t.cancel()  # сам wait ничего не отменяет
asyncio.run(main())
# Python 3.11+
import asyncio
async def main():
    coro = asyncio.sleep(0.01)
    try:
        await asyncio.wait([coro])
    except TypeError:
        print('нужны задачи, а не корутины')  # → нужны задачи, а не корутины
    finally:
        coro.close()
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy