On this page
asyncio
Prev: ast | Up: stdlib_module | Next: atexit
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — asyncio
Tags: #public #python3 #stdlib
Import
import asyncio
Overview
Single-threaded cooperative concurrency framework for high-throughput I/O (network sockets, HTTP clients, subprocesses, streams, queues) using async/await coroutines and an event loop. Reach for asyncio for managing many concurrent I/O tasks cleanly; use threading for blocking synchronous I/O or multiprocessing for CPU-bound work.
Quick Start
import asyncio
async def fetch_item(item_id: int) -> str:
await asyncio.sleep(0.01)
return f"item-{item_id}"
async def main() -> list[str]:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch_item(i)) for i in range(3)]
return [t.result() for t in tasks]
assert asyncio.run(main()) == ["item-0", "item-1", "item-2"]
Implementation Walkthrough
1. Bounded Concurrency & Timeouts (Semaphore + asyncio.timeout)
Always cap fan-out concurrency with a Semaphore and bound slow calls with asyncio.timeout() (Python 3.11+):
import asyncio
async def bounded_work(sem: asyncio.Semaphore, n: int) -> int:
async with sem:
async with asyncio.timeout(2.0):
await asyncio.sleep(0.01)
return n * 2
async def run_batch(items: list[int], limit: int = 4) -> list[int]:
sem = asyncio.Semaphore(limit)
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(bounded_work(sem, x)) for x in items]
return [t.result() for t in tasks]
2. Offloading Blocking Synchronous Code with asyncio.to_thread()
import asyncio
from pathlib import Path
async def read_file_async(path: Path) -> str:
return await asyncio.to_thread(path.read_text, encoding="utf-8")
Gotchas & Boundaries
- Never call blocking I/O (
time.sleep,urllib.request, sync disk I/O) directly insideasync def: It freezes the entire event loop; useasyncio.to_thread()or async libraries. - Keep references to background tasks: Fire-and-forget
asyncio.create_task(...)without storing a reference can be garbage-collected mid-flight; preferasyncio.TaskGroupfor structured lifetimes. - Never swallow
asyncio.CancelledError: It inherits fromBaseException; if you catch it for cleanup, always re-raise it. - Prefer
asyncio.TaskGroup()overasyncio.gather()(Python 3.11+) so sibling tasks are cleanly cancelled if one fails.
Common Functions
- asyncio.all_tasks() —
all_tasks(loop=None)— Return a set of all tasks for the loop. - asyncio.as_completed() —
as_completed(fs, *, timeout=None)— Create an iterator of awaitables or their results in completion order. - asyncio.capture_call_graph() —
capture_call_graph(future: _asyncio.Future | None = None, /, *, depth: int = 1, limit: int | None = None) -> asyncio.graph.FutureCallGraph | None— Capture the async call graph for the current task or the provided Future. - asyncio.create_eager_task_factory() —
create_eager_task_factory(custom_task_constructor)— Create a function suitable for use as a task factory on an event-loop. - asyncio.create_subprocess_exec() —
create_subprocess_exec(program, *args, stdin=None, stdout=None, stderr=None, limit=65536, **kwds)—asyncio.create_subprocess_exec()function. - asyncio.create_subprocess_shell() —
create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, limit=65536, **kwds)—asyncio.create_subprocess_shell()function. - asyncio.create_task() —
create_task(coro, **kwargs)— Schedule the execution of a coroutine object in a spawn task. - asyncio.current_task() —
current_task(loop=None)— Return a currently executed task. - asyncio.eager_task_factory() —
eager_task_factory(loop, coro, *, eager_start=True, **kwargs)—asyncio.eager_task_factory()function. - asyncio.ensure_future() —
ensure_future(coro_or_future, *, loop=None)— Wrap a coroutine or an awaitable in a future. - asyncio.format_call_graph() —
format_call_graph(future: _asyncio.Future | None = None, /, *, depth: int = 1, limit: int | None = None) -> str— Return the async call graph as a string forfuture. - asyncio.future_add_to_awaited_by() —
future_add_to_awaited_by(fut, waiter, /)— Record thatfutis awaited on bywaiter. - asyncio.future_discard_from_awaited_by() —
future_discard_from_awaited_by(fut, waiter, /)—asyncio.future_discard_from_awaited_by()function. - asyncio.gather() —
gather(*coros_or_futures, return_exceptions=False)— Return a future aggregating results from the given coroutines/futures. - asyncio.get_event_loop() —
get_event_loop()— Return an asyncio event loop. - asyncio.get_event_loop_policy() —
get_event_loop_policy()—asyncio.get_event_loop_policy()function. - asyncio.get_running_loop() —
get_running_loop()— Return the running event loop. Raise a RuntimeError if there is none. - asyncio.iscoroutine() —
iscoroutine(obj)— Return True if obj is a coroutine object. - asyncio.iscoroutinefunction() —
iscoroutinefunction(func)— Return True if func is a decorated coroutine function. - asyncio.isfuture() —
isfuture(obj)— Check for a Future. - asyncio.new_event_loop() —
new_event_loop()— Equivalent to calling get_event_loop_policy().new_event_loop(). - asyncio.open_connection() —
open_connection(host=None, port=None, *, limit=65536, **kwds)— A wrapper for create_connection() returning a (reader, writer) pair. - asyncio.open_unix_connection() —
open_unix_connection(path=None, *, limit=65536, **kwds)— Similar toopen_connectionbut works with UNIX Domain Sockets. - asyncio.print_call_graph() —
print_call_graph(future: _asyncio.Future | None = None, /, *, file: io.Writer[str] | None = None, depth: int = 1, limit: int | None = None) -> None— Print the async call graph for the current task or the provided Future. - asyncio.run() —
run(main, *, debug=None, loop_factory=None)— Execute the coroutine and return the result. - asyncio.run_coroutine_threadsafe() —
run_coroutine_threadsafe(coro, loop)— Submit a coroutine object to a given event loop. - asyncio.set_event_loop() —
set_event_loop(loop)— Equivalent to calling get_event_loop_policy().set_event_loop(loop). - asyncio.set_event_loop_policy() —
set_event_loop_policy(policy)—asyncio.set_event_loop_policy()function. - asyncio.shield() —
shield(arg)— Wait for a future, shielding it from cancellation. - asyncio.sleep() —
sleep(delay, result=None)— Coroutine that completes after a given time (in seconds). - asyncio.start_server() —
start_server(client_connected_cb, host=None, port=None, *, limit=65536, **kwds)— Start a socket server, call back for each client connected. - asyncio.start_unix_server() —
start_unix_server(client_connected_cb, path=None, *, limit=65536, **kwds)— Similar tostart_serverbut works with UNIX Domain Sockets. - asyncio.timeout() —
timeout(delay: float | None) -> asyncio.timeouts.Timeout— Timeout async context manager. - asyncio.timeout_at() —
timeout_at(when: float | None) -> asyncio.timeouts.Timeout— Schedule the timeout at absolute time. - asyncio.to_thread() —
to_thread(func, /, *args, **kwargs)— Asynchronously run function func in a separate thread.
Classes & Objects
- asyncio.AbstractEventLoop — Abstract event loop. (Methods:
.add_reader(),.add_signal_handler(),.add_writer(),.call_at(),.call_exception_handler(),.call_later()) - asyncio.AbstractServer — Abstract server returned by create_server(). (Methods:
.abort_clients(),.close(),.close_clients(),.get_loop(),.is_serving(),.serve_forever()) - asyncio.Barrier — Asyncio equivalent to threading.Barrier Implements a Barrier primitive. (Methods:
.abort(),.broken(),.n_waiting(),.parties(),.reset(),.wait()) - asyncio.BaseEventLoop —
asyncio.BaseEventLoopclass. (Methods:.add_reader(),.add_signal_handler(),.add_writer(),.call_at(),.call_exception_handler(),.call_later()) - asyncio.BaseProtocol — Common base class for protocol interfaces. (Methods:
.connection_lost(),.connection_made(),.pause_writing(),.resume_writing()) - asyncio.BaseTransport — Base class for transports. (Methods:
.close(),.get_extra_info(),.get_protocol(),.is_closing(),.set_protocol()) - asyncio.BoundedSemaphore — A bounded semaphore implementation. (Methods:
.acquire(),.locked(),.release()) - asyncio.BrokenBarrierError — Barrier is broken by barrier.abort() call. (Methods:
.add_note(),.with_traceback()) - asyncio.BufferedProtocol — Interface for stream protocol with manual buffer control. (Methods:
.buffer_updated(),.connection_lost(),.connection_made(),.eof_received(),.get_buffer(),.pause_writing()) - asyncio.CancelledError — The Future or Task was cancelled. (Methods:
.add_note(),.with_traceback()) - asyncio.Condition — Asynchronous equivalent to threading.Condition. (Methods:
.notify(),.notify_all(),.wait(),.wait_for()) - asyncio.DatagramProtocol — Interface for datagram protocol. (Methods:
.connection_lost(),.connection_made(),.datagram_received(),.error_received(),.pause_writing(),.resume_writing()) - asyncio.DatagramTransport — Interface for datagram (UDP) transports. (Methods:
.abort(),.close(),.get_extra_info(),.get_protocol(),.is_closing(),.sendto()) - asyncio.Event — Asynchronous equivalent to threading.Event. (Methods:
.clear(),.is_set(),.set(),.wait()) - asyncio.EventLoop — Unix event loop. (Methods:
.add_reader(),.add_signal_handler(),.add_writer(),.call_at(),.call_exception_handler(),.call_later()) - asyncio.FrameCallGraphEntry — FrameCallGraphEntry(frame: frame)
- asyncio.Future — This class is almost compatible with concurrent.futures.Future. (Methods:
.add_done_callback(),.cancel(),.cancelled(),.done(),.exception(),.get_loop()) - asyncio.FutureCallGraph — FutureCallGraph(future: _asyncio.Future, call_stack: tuple['FrameCallGraphEntry', ...], awaited_by: tuple['FutureCallGraph', ...])
- asyncio.Handle — Object returned by callback registration methods. (Methods:
.cancel(),.cancelled(),.get_context()) - asyncio.IncompleteReadError — Incomplete read error. Attributes: - partial: read bytes string before the end of stream was reached - expected: total number of expected bytes (or None if unknown) (Methods:
.add_note(),.with_traceback())
Constants & Attributes
asyncio.ALL_COMPLETED(str) ='ALL_COMPLETED'asyncio.FIRST_COMPLETED(str) ='FIRST_COMPLETED'asyncio.FIRST_EXCEPTION(str) ='FIRST_EXCEPTION'
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/ast
- tuts/python3/stdlib_module/asyncio/AbstractEventLoop
- tuts/python3/stdlib_module/asyncio/AbstractServer
- tuts/python3/stdlib_module/asyncio/all_tasks
- tuts/python3/stdlib_module/asyncio/as_completed
- tuts/python3/stdlib_module/asyncio/Barrier
- tuts/python3/stdlib_module/asyncio/BaseEventLoop
- tuts/python3/stdlib_module/asyncio/BaseProtocol
- tuts/python3/stdlib_module/asyncio/BaseTransport
- tuts/python3/stdlib_module/asyncio/BoundedSemaphore
- tuts/python3/stdlib_module/asyncio/BrokenBarrierError
- tuts/python3/stdlib_module/asyncio/BufferedProtocol
- tuts/python3/stdlib_module/asyncio/CancelledError
- tuts/python3/stdlib_module/asyncio/capture_call_graph
- tuts/python3/stdlib_module/asyncio/Condition
- tuts/python3/stdlib_module/asyncio/create_eager_task_factory
- tuts/python3/stdlib_module/asyncio/create_subprocess_exec
- tuts/python3/stdlib_module/asyncio/create_subprocess_shell
- tuts/python3/stdlib_module/asyncio/create_task
- tuts/python3/stdlib_module/asyncio/current_task
- tuts/python3/stdlib_module/asyncio/DatagramProtocol
- tuts/python3/stdlib_module/asyncio/DatagramTransport
- tuts/python3/stdlib_module/asyncio/eager_task_factory
- tuts/python3/stdlib_module/asyncio/ensure_future
- tuts/python3/stdlib_module/asyncio/Event
- tuts/python3/stdlib_module/asyncio/EventLoop
- tuts/python3/stdlib_module/asyncio/format_call_graph
- tuts/python3/stdlib_module/asyncio/FrameCallGraphEntry
- tuts/python3/stdlib_module/asyncio/Future
- tuts/python3/stdlib_module/asyncio/future_add_to_awaited_by
- tuts/python3/stdlib_module/asyncio/future_discard_from_awaited_by
- tuts/python3/stdlib_module/asyncio/FutureCallGraph
- tuts/python3/stdlib_module/asyncio/gather
- tuts/python3/stdlib_module/asyncio/get_event_loop
- tuts/python3/stdlib_module/asyncio/get_event_loop_policy
- tuts/python3/stdlib_module/asyncio/get_running_loop
- tuts/python3/stdlib_module/asyncio/Handle
- tuts/python3/stdlib_module/asyncio/IncompleteReadError
- tuts/python3/stdlib_module/asyncio/iscoroutine
- tuts/python3/stdlib_module/asyncio/iscoroutinefunction
- tuts/python3/stdlib_module/asyncio/isfuture
- tuts/python3/stdlib_module/asyncio/new_event_loop
- tuts/python3/stdlib_module/asyncio/open_connection
- tuts/python3/stdlib_module/asyncio/open_unix_connection
- tuts/python3/stdlib_module/asyncio/print_call_graph
- tuts/python3/stdlib_module/asyncio/run
- tuts/python3/stdlib_module/asyncio/run_coroutine_threadsafe
- tuts/python3/stdlib_module/asyncio/set_event_loop
- tuts/python3/stdlib_module/asyncio/set_event_loop_policy
- tuts/python3/stdlib_module/asyncio/shield
- tuts/python3/stdlib_module/asyncio/sleep
- tuts/python3/stdlib_module/asyncio/start_server
- tuts/python3/stdlib_module/asyncio/start_unix_server
- tuts/python3/stdlib_module/asyncio/timeout
- tuts/python3/stdlib_module/asyncio/timeout_at
- tuts/python3/stdlib_module/asyncio/to_thread
- tuts/python3/stdlib_module/atexit
- tuts/python3/stdlib_module/contextvars
- tuts/python3/stdlib_module/multiprocessing
- tuts/python3/stdlib_module/sched
- tuts/python3/stdlib_module/select
- tuts/python3/stdlib_module/selectors
- tuts/python3/stdlib_module/signal
- tuts/python3/stdlib_module/socket
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/advanced_python_internals
- tuts/python3/tutorials/advanced_python_internals/concurrency_and_parallelism
Related notes
- tuts/python3/stdlib_module/ast Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/AbstractEventLoop Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/AbstractServer Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/all_tasks Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/as_completed Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/Barrier Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/BaseEventLoop Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/BaseProtocol Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/BaseTransport Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/BoundedSemaphore Linked here; links to this page; shared tags: #stdlib