Convert Figma logo to code with AI

python-trio logotrio

Trio – a friendly Python library for async concurrency and I/O

6,078
331
6,078
304

Top Related Projects

4,024

Good Curio!

10,269

Ultra fast asyncio event loop.

21,674

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

6,229

Coroutine-based concurrency library for Python

12,973

A next generation HTTP client for Python. 🦋

Quick Overview

Trio is a modern, friendly Python library for writing asynchronous applications. It focuses on making concurrent programming more accessible and less error-prone by providing a structured concurrency model. Trio aims to be easier to use and understand compared to other async libraries while still offering powerful features.

Pros

  • Simple and intuitive API, making it easier for beginners to learn async programming
  • Structured concurrency model helps prevent common pitfalls like forgotten tasks or race conditions
  • Excellent documentation and community support
  • Built-in support for cancellation and timeouts

Cons

  • Smaller ecosystem compared to asyncio, which may limit available third-party libraries
  • Not as widely adopted in production environments as asyncio
  • May require rewriting existing asyncio-based code to take full advantage of Trio's features
  • Performance might be slightly lower than asyncio in some scenarios

Code Examples

  1. Basic async function:
import trio

async def hello():
    await trio.sleep(1)
    print("Hello, world!")

trio.run(hello)
  1. Concurrent tasks with nursery:
import trio

async def task(name):
    print(f"Task {name} starting")
    await trio.sleep(1)
    print(f"Task {name} finished")

async def main():
    async with trio.open_nursery() as nursery:
        for i in range(3):
            nursery.start_soon(task, f"Task {i}")

trio.run(main)
  1. Cancellation example:
import trio

async def child():
    print("child: started!")
    try:
        await trio.sleep_forever()
    except trio.Cancelled:
        print("child: cancelled!")

async def parent():
    print("parent: starting...")
    async with trio.open_nursery() as nursery:
        nursery.start_soon(child)
        await trio.sleep(1)
        print("parent: cancelling nursery...")
        nursery.cancel_scope.cancel()
    print("parent: nursery cancelled")

trio.run(parent)

Getting Started

To get started with Trio, first install it using pip:

pip install trio

Then, you can create a simple async program:

import trio

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

trio.run(main)

This program will print "Hello", wait for 1 second, and then print "World". To run more complex concurrent tasks, use trio.open_nursery() as shown in the code examples above.

Competitor Comparisons

4,024

Good Curio!

Pros of Curio

  • Simpler and more lightweight implementation
  • Easier to understand and modify for advanced users
  • More closely follows Python's core language features

Cons of Curio

  • Smaller community and ecosystem compared to Trio
  • Less comprehensive documentation and tutorials
  • Fewer built-in features and abstractions

Code Comparison

Curio example:

import curio

async def hello():
    await curio.sleep(1)
    print('Hello, World!')

curio.run(hello)

Trio example:

import trio

async def hello():
    await trio.sleep(1)
    print('Hello, World!')

trio.run(hello)

Both Curio and Trio are asynchronous I/O libraries for Python, aiming to provide a simpler alternative to asyncio. They share similar syntax and concepts, making it easy for developers to switch between them.

Curio focuses on simplicity and staying close to Python's core features, which can be beneficial for those who want to understand the underlying mechanisms. However, Trio offers a more comprehensive ecosystem, better documentation, and additional safety features, making it more suitable for larger projects and less experienced developers.

The code examples demonstrate that both libraries have similar basic usage patterns, with only minor differences in import statements and run functions. This similarity allows for relatively easy migration between the two libraries if needed.

10,269

Ultra fast asyncio event loop.

Pros of uvloop

  • Significantly faster performance, often 2-4x speedup over asyncio
  • Drop-in replacement for asyncio event loop, easy integration
  • Written in Cython for optimized C-speed operations

Cons of uvloop

  • Limited to Unix-like systems, not compatible with Windows
  • Less focus on structured concurrency and safety compared to Trio
  • May introduce subtle behavioral differences from the standard asyncio loop

Code Comparison

uvloop:

import asyncio
import uvloop

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
asyncio.run(main())

Trio:

import trio

trio.run(main)

Key Differences

  • Trio emphasizes structured concurrency and safety, while uvloop focuses on raw performance
  • uvloop is a drop-in replacement for asyncio, whereas Trio is an alternative async framework
  • Trio provides built-in cancellation and timeout features, which require more manual handling in uvloop/asyncio

Use Cases

  • Choose uvloop for maximum performance on Unix systems with existing asyncio codebases
  • Opt for Trio when prioritizing code clarity, safety, and cross-platform compatibility

Both libraries offer valuable improvements to Python's async capabilities, with uvloop excelling in speed and Trio in safety and structure.

21,674

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

Pros of Tornado

  • Mature and battle-tested framework with a long history of production use
  • Extensive documentation and large community support
  • Built-in support for WebSockets and long polling

Cons of Tornado

  • Single-threaded event loop can be a limitation for CPU-bound tasks
  • Less intuitive for developers accustomed to synchronous programming
  • Callback-based programming can lead to "callback hell" in complex applications

Code Comparison

Tornado example:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, World!")

app = tornado.web.Application([(r"/", MainHandler)])
app.listen(8888)
tornado.ioloop.IOLoop.current().start()

Trio example:

async def hello_world(request):
    await request.send_html("Hello, World!")

async def main():
    await trio.serve_tcp(hello_world, 8888)

trio.run(main)

Both Tornado and Trio are asynchronous frameworks for Python, but they differ in their approach to concurrency. Tornado uses a callback-based model, while Trio employs structured concurrency with async/await syntax. Trio aims to make concurrent programming more intuitive and less error-prone, while Tornado offers a more established ecosystem and broader feature set for web applications.

6,229

Coroutine-based concurrency library for Python

Pros of gevent

  • Mature and widely adopted in production environments
  • Seamless integration with existing synchronous code through monkey-patching
  • Extensive ecosystem of compatible libraries and extensions

Cons of gevent

  • Relies on monkey-patching, which can lead to unexpected behavior and compatibility issues
  • Less explicit about concurrency, making it harder to reason about code execution
  • Limited support for newer Python features and async/await syntax

Code Comparison

gevent:

import gevent

def fetch(url):
    # Simulated network request
    gevent.sleep(1)
    return f"Result from {url}"

urls = ['http://example.com', 'http://example.org']
jobs = [gevent.spawn(fetch, url) for url in urls]
results = gevent.joinall(jobs)

trio:

import trio

async def fetch(url):
    # Simulated network request
    await trio.sleep(1)
    return f"Result from {url}"

async def main():
    urls = ['http://example.com', 'http://example.org']
    async with trio.open_nursery() as nursery:
        results = await nursery.start_soon(fetch, url) for url in urls

Both gevent and trio provide concurrency solutions for Python, but they differ in their approach and syntax. gevent offers easier integration with existing codebases, while trio provides a more explicit and structured approach to asynchronous programming.

12,973

A next generation HTTP client for Python. 🦋

Pros of httpx

  • Focused specifically on HTTP client functionality, providing a more streamlined and purpose-built solution
  • Supports both sync and async APIs, offering flexibility for different programming styles
  • Includes built-in support for HTTP/2 and advanced features like connection pooling

Cons of httpx

  • Limited to HTTP-related tasks, whereas Trio is a general-purpose async library
  • May have a steeper learning curve for those unfamiliar with async programming concepts
  • Less mature project compared to Trio, potentially with fewer community resources

Code Comparison

httpx (async example):

async with httpx.AsyncClient() as client:
    response = await client.get('https://example.com')
    print(response.text)

Trio (general async example):

async def main():
    async with trio.open_nursery() as nursery:
        nursery.start_soon(some_async_function)
        nursery.start_soon(another_async_function)

trio.run(main)

Both libraries offer async capabilities, but httpx is specifically designed for HTTP requests, while Trio provides a more general-purpose async framework. httpx's API is more focused on HTTP operations, whereas Trio's API is broader and can be used for various types of concurrent programming tasks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.. image:: https://img.shields.io/badge/chat-join%20now-blue.svg :target: https://gitter.im/python-trio/general :alt: Join chatroom

.. image:: https://img.shields.io/badge/forum-join%20now-blue.svg :target: https://trio.discourse.group :alt: Join forum

.. image:: https://img.shields.io/badge/docs-read%20now-blue.svg :target: https://trio.readthedocs.io :alt: Documentation

.. image:: https://img.shields.io/pypi/v/trio.svg :target: https://pypi.org/project/trio :alt: Latest PyPi version

.. image:: https://img.shields.io/conda/vn/conda-forge/trio.svg :target: https://anaconda.org/conda-forge/trio :alt: Latest conda-forge version

.. image:: https://codecov.io/gh/python-trio/trio/branch/main/graph/badge.svg :target: https://codecov.io/gh/python-trio/trio :alt: Test coverage

Trio – a friendly Python library for async concurrency and I/O

.. image:: https://raw.githubusercontent.com/python-trio/trio/9b0bec646a31e0d0f67b8b6ecc6939726faf3e17/logo/logo-with-background.svg :width: 200px :align: right

The Trio project aims to produce a production-quality, permissively licensed <https://github.com/python-trio/trio/blob/main/LICENSE>__, async/await-native I/O library for Python. Like all async libraries, its main purpose is to help you write programs that do multiple things at the same time with parallelized I/O. A web spider that wants to fetch lots of pages in parallel, a web server that needs to juggle lots of downloads and websocket connections simultaneously, a process supervisor monitoring multiple subprocesses... that sort of thing. Compared to other libraries, Trio attempts to distinguish itself with an obsessive focus on usability and correctness. Concurrency is complicated; we try to make it easy to get things right.

Trio was built from the ground up to take advantage of the latest Python features <https://www.python.org/dev/peps/pep-0492/>, and draws inspiration from many sources <https://github.com/python-trio/trio/wiki/Reading-list>, in particular Dave Beazley's Curio <https://curio.readthedocs.io/>. The resulting design is radically simpler than older competitors like asyncio <https://docs.python.org/3/library/asyncio.html> and Twisted <https://twistedmatrix.com/>, yet just as capable. Trio is the Python I/O library I always wanted; I find it makes building I/O-oriented programs easier, less error-prone, and just plain more fun. Perhaps you'll find the same <https://github.com/python-trio/trio/wiki/Testimonials>.

This project is young and still somewhat experimental: the overall design is solid, and the existing features are fully tested and documented, but you may encounter missing functionality or rough edges. We do encourage you to use it, but you should read and subscribe to issue #1 <https://github.com/python-trio/trio/issues/1>__ to get a warning and a chance to give feedback about any compatibility-breaking changes.

Where to next?

I want to try it out! Awesome! We have a friendly tutorial <https://trio.readthedocs.io/en/stable/tutorial.html>__ to get you started; no prior experience with async coding is required.

Ugh, I don't want to read all that – show me some code! If you're impatient, then here's a simple concurrency example <https://trio.readthedocs.io/en/stable/tutorial.html#tutorial-example-tasks-intro>, an echo client <https://trio.readthedocs.io/en/stable/tutorial.html#tutorial-echo-client-example>, and an echo server <https://trio.readthedocs.io/en/stable/tutorial.html#tutorial-echo-server-example>__.

How does Trio make programs easier to read and reason about than competing approaches? Trio is based on a new way of thinking that we call "structured concurrency". The best theoretical introduction is the article Notes on structured concurrency, or: Go statement considered harmful <https://vorpus.org/blog/notes-on-structured-concurrency-or-go-statement-considered-harmful/>. Or, check out this talk at PyCon 2018 <https://www.youtube.com/watch?v=oLkfnc_UMcE> to see a demonstration of implementing the "Happy Eyeballs" algorithm in an older library versus Trio.

Cool, but will it work on my system? Probably! As long as you have some kind of Python 3.8-or-better (CPython or currently maintained versions of PyPy3 <https://doc.pypy.org/en/latest/faq.html#which-python-versions-does-pypy-implement>__ are both fine), and are using Linux, macOS, Windows, or FreeBSD, then Trio will work. Other environments might work too, but those are the ones we test on. And all of our dependencies are pure Python, except for CFFI on Windows, which has wheels available, so installation should be easy (no C compiler needed).

I tried it, but it's not working. Sorry to hear that! You can try asking for help in our chat room <https://gitter.im/python-trio/general>__ or forum <https://trio.discourse.group>, filing a bug <https://github.com/python-trio/trio/issues/new>, or posting a question on StackOverflow <https://stackoverflow.com/questions/ask?tags=python+python-trio>__, and we'll do our best to help you out.

Trio is awesome, and I want to help make it more awesome! You're the best! There's tons of work to do – filling in missing functionality, building up an ecosystem of Trio-using libraries, usability testing (e.g., maybe try teaching yourself or a friend to use Trio and make a list of every error message you hit and place where you got confused?), improving the docs, ... check out our guide for contributors <https://trio.readthedocs.io/en/stable/contributing.html>__!

I don't have any immediate plans to use it, but I love geeking out about I/O library design! That's a little weird? But let's be honest, you'll fit in great around here. We have a whole sub-forum for discussing structured concurrency <https://trio.discourse.group/c/structured-concurrency>__ (developers of other systems welcome!). Or check out our discussion of design choices <https://trio.readthedocs.io/en/stable/design.html#user-level-api-principles>, reading list <https://github.com/python-trio/trio/wiki/Reading-list>, and issues tagged design-discussion <https://github.com/python-trio/trio/labels/design%20discussion>__.

I want to make sure my company's lawyers won't get angry at me! No worries, Trio is permissively licensed under your choice of MIT or Apache 2. See LICENSE <https://github.com/python-trio/trio/blob/main/LICENSE>__ for details.

Code of conduct

Contributors are requested to follow our code of conduct <https://trio.readthedocs.io/en/stable/code-of-conduct.html>__ in all project spaces.