On this page
  1. asyncio
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Bounded Concurrency & Timeouts (Semaphore + asyncio.timeout)
  7. 2. Offloading Blocking Synchronous Code with asyncio.to_thread()
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes