Beyond Asyncio: Exploring Asynchronous Programming Options in Python

Mar 25, 2024 ยท 2 min read

Asyncio is Python's built-in asynchronous programming framework, allowing you to write non-blocking code by using async/await syntax. However, asyncio is not the only game in town for async in Python. Here are some alternative options:

Twisted

Twisted predates asyncio and has been a popular async framework for Python for many years. Like asyncio, it is based on an event loop and deferreds (similar to asyncio futures).

Twisted supports not only TCP servers but also protocols like HTTP, DNS, SSH, and more out of the box. It has a steeper learning curve than asyncio but is very powerful.

from twisted.internet import reactor, protocol

class Echo(protocol.Protocol):
    def dataReceived(self, data):
        self.transport.write(data)

def main():
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    reactor.listenTCP(8000,factory)
    reactor.run()

if __name__ == '__main__':
    main()

Trio

Trio is a newer async framework that fixes some of the rough edges from asyncio like canceled errors. It uses Python 3.5+ async syntax under the hood but provides a simpler API.

Trio makes it easy to perform multiple tasks concurrently:

import trio

async def child1():
   print("hello from child 1!")

async def child2():
   print("hello from child 2!")
   
async def parent():
   async with trio.open_nursery() as nursery:
      nursery.start_soon(child1)
      nursery.start_soon(child2)

trio.run(parent)

Curio

Curio is another popular async framework designed to be high-performance and include useful abstractions like queues and locks for common async patterns. It uses coroutines and has a similar API to asyncio.

So while asyncio is gaining adoption, developers should know they have choices like Twisted, Trio, or Curio for their asynchronous programming needs in Python. Each has its own strengths to consider when building modern, non-blocking applications.

Browse by tags:

Browse by language:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: