AnyIO

4.13.0 · active · verified Sat Mar 28

AnyIO is a high-level asynchronous networking and concurrency library that runs on top of either asyncio or Trio, implementing Trio-like structured concurrency on both backends. Code written against AnyIO's API runs unmodified on either backend, allowing incremental adoption. Current stable version is 4.13.0, with an active monthly-ish release cadence under Alex Grönholm (agronholm).

Warnings

Install

Imports

Quickstart

Demonstrates concurrent task groups, move_on_after timeout scopes, and offloading blocking calls to a worker thread — all backend-agnostic.

import anyio

async def fetch(name: str, delay: float) -> None:
    print(f'{name}: starting')
    await anyio.sleep(delay)
    print(f'{name}: done after {delay}s')

async def main() -> None:
    # Task group: all tasks run concurrently; exceptions surface as ExceptionGroup
    async with anyio.create_task_group() as tg:
        tg.start_soon(fetch, 'task-A', 1.0)
        tg.start_soon(fetch, 'task-B', 0.5)

    # Timeout via CancelScope
    with anyio.move_on_after(2.0) as scope:
        await anyio.sleep(5)
    if scope.cancelled_caught:
        print('timed out (moved on)')

    # Run a blocking call in a thread
    import time
    result = await anyio.to_thread.run_sync(time.strftime, '%X')
    print('wall-clock time from thread:', result)

if __name__ == '__main__':
    # Default backend is asyncio; swap to 'trio' with no code changes
    anyio.run(main, backend='asyncio')

view raw JSON →