Skip to content

Instantly share code, notes, and snippets.

@npodonnell
Last active June 3, 2021 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npodonnell/920eb3c2daa28080912a1f6f171f57c7 to your computer and use it in GitHub Desktop.
Save npodonnell/920eb3c2daa28080912a1f6f171f57c7 to your computer and use it in GitHub Desktop.
Trio Cheatsheet

Trio Cheatsheet

N. P. O'Donnell, 2021

Simple Trio Program

import trio


async def main():
    print("hello")


trio.run(main)

Sleeping

To sleep, use trio.sleep:

async def main():
    trio.sleep(3.)
    print("hello after 3s")

Nurseries

Nurseries are used for running multiple tasks:

import trio


async def waiter(sleep_s):
    await trio.sleep(sleep_s)
    print(f"done waiting {sleep_s}s")


async def main():
    print("about to wait...")
    async with trio.open_nursery() as n:
        n.start_soon(waiter, 3)
        n.start_soon(waiter, 5)
        print("waiting...")
    print("all done")


trio.run(main)

Implementing Timeouuts

Timeouts can be implemented using move_on_after:

async def main():
    with trio.move_on_after(6.):
        await waiter(3.)
        await waiter(2.)
        print("got everything done")
    print("moving on")

Timeout with Failure

Use fail_after to raise an exception if a task does not complete on time:

async def main():
    try:
        with trio.fail_after(4.):
            async with trio.open_nursery() as n:
                n.start_soon(waiter, 3.)
                n.start_soon(waiter, 5.)
        print("didn't fail!")
    except trio.TooSlowError as e:
        print("failed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment