On this page
asyncio.gather
Prev: asyncio.FutureCallGraph | Up: asyncio | Next: asyncio.get_event_loop
Rel: asyncio.AbstractEventLoop, asyncio.AbstractServer, asyncio.all_tasks, asyncio.as_completed
Ref: docs.python.org — asyncio.gather
Tags: #public #python3 #stdlib #asyncio
Import
import asyncio
from asyncio import gather
Signature & Overview
asyncio.gather(*coros_or_futures, return_exceptions=False)
Return a future aggregating results from the given coroutines/futures.
Usage
import asyncio
async def sq(n: int) -> int:
await asyncio.sleep(0)
return n * n
async def main():
res = await asyncio.gather(sq(2), sq(3), sq(4))
assert res == [4, 9, 16]
asyncio.run(main())
Gotchas
- Results keep input order: Even if
sq(4)finishes first, the list matches the argument order. - Exception behavior: By default the first exception propagates while sibling tasks keep running; pass
return_exceptions=Trueto collect exceptions as values, or useasyncio.TaskGroup(Python 3.11+) for structured cancellation.
REPL Inspect
from asyncio import gather
help(gather)
Linked from
Related notes
- tuts/python3/stdlib_module/asyncio/FutureCallGraph Linked here; links to this page; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/get_event_loop Linked here; links to this page; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/AbstractEventLoop Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/AbstractServer Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/all_tasks Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/as_completed Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/Barrier shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/BaseEventLoop shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/BaseProtocol shared tags: #asyncio, #stdlib