1 min read

Python Trio Library

Trio is a modern library for asynchronous concurrency in Python. It is designed to be easier to use and harder to make mistakes with than asyncio, focusing on "structured concurrency".

Installation

pip install trio

Basic Usage

Trio uses async/await syntax but requires a trio.run() entry point.

import trio

async def main():
    print("Hello")
    await trio.sleep(1)
    print("World")

trio.run(main)

Nurseries (Structured Concurrency)

In Trio, you spawn tasks inside a "nursery". The nursery block doesn't exit until all tasks inside it have completed.

import trio

async def child1():
    print("Child 1 started")
    await trio.sleep(1)
    print("Child 1 finished")

async def child2():
    print("Child 2 started")
    await trio.sleep(0.5)
    print("Child 2 finished")

async def main():
    async with trio.open_nursery() as nursery:
        nursery.start_soon(child1)
        nursery.start_soon(child2)
    print("All children finished")

trio.run(main)

Timeouts

Trio makes timeouts easy and safe with context managers.

import trio

async def main():
    with trio.move_on_after(2):
        await trio.sleep(5)
        print("This won't print")
    print("Timeout expired, continuing...")

trio.run(main)

Cancellation

Cancellation is handled via "cancel scopes".

import trio

async def main():
    with trio.CancelScope() as scope:
        scope.cancel()
        await trio.sleep(1)
        print("This won't print")

trio.run(main)

programming/python/python