Learn asyncio if you come from Twisted

The Twisted project is probably one of the oldest libraries that supports asynchronous programming in Python. It has been used by many programmers to develop a variety of applications. It supports many network protocols and can be used for many different types of network programming. In fact, asyncio was heavily inspired by Twisted. The expertise of several Twisted developers had been incorporated in asyncio. Soon, there will be a version of Twisted that is based on asyncio.

Rosetta Stone

This tables shows equivalent concepts in Twisted and asyncio.

Twisted asyncio
Deferred asyncio.Future
deferToThread(func) loop.run_in_executor(None, func)
@inlineCallbacks async def
reactor.run() loop.run_forever()

Deferred example

This small example shows two equivalent programs, one implemented in Twisted and one in asyncio.

Twisted asyncio

Basic Twisted example using deferred:

from twisted.internet import defer
from twisted.internet import reactor


def multiply(x):
    result = x * 2
    d = defer.Deferred()
    reactor.callLater(1.0, d.callback,
                      result)
    return d


def step1(x):
    return multiply(x)


def step2(result):
    print("result: %s" % result)

    reactor.stop()


d = defer.Deferred()
d.addCallback(step1)
d.addCallback(step2)
d.callback(5)

reactor.run()

Similar example written using asyncio:

import asyncio


async def multiply(x):
    result = x * 2
    await asyncio.sleep(1)
    return result


async def steps(x):
    result = await multiply(x)
    print("result: %s" % result)


loop = asyncio.get_event_loop()
coro = steps(5)
loop.run_until_complete(coro)
loop.close()