Twisted to asyncio - gelisa/txdbus GitHub Wiki

Since asyncio is heavily inspired by Twisted it's not really hard to spot the similarities between the both.

For convenience and for future references, here are a crude mapping between some common facilities and components.

twisted.internet.protocol.Protocol -> asyncio.Protocol

This is probably the API that reassembles most closely between both libraries, even naming conventions and method signatures are the same. However the way they work in the background might differ so be careful when porting this not to make the assumption that they are the same.

twisted.internet.reactor -> asyncio.get_event_loop()

Twisted already has a usable event loop setup upon import of twisted.internet (the reactor object). asyncio however does not instantiate such an object by default, this is done by calling asyncio.get_event_loop().

Good praxis is to preserve the reference of the used EventLoop instance in all objects that might need to use it's EventLoop for further asyncio tasks.

twisted.internet.defer.Deferred -> asyncio.Future

Deferred, Promise, Future and Result are all commonly used names for a pretty much same way of dealing with asynchronous results. The modules has very similar method signatures and works in pretty much the same way.

twisted.internet.protocol.Factory -> lambda

In twisted in order to create an endpoint and associate it with a Protocol a Factory is used. The Factory is subclassed (or used as is) in conjunction with an implemented Protocol and is written in a way that will create an instance of a Protocol class and associate the factory with it.

The factory is then called with the endpoint to associate the endpoint with the protocol.

In asyncio this is called the Transport and Protocol low-level API. A Transport is created through a factory method on the EventLoop instance, with a function that factories the Protocol associated with it. Example

twisted.internet.endpoints.{UNIX,TCP4}{Server,Client}Endpoint

The asyncio version of these classes are not really a commonly subclassed API. There are however objects in asyncio that closely reassembles these corresponding objects in twisted, which is created by the factory methods on the EventLoop.

  • t.i.e.UNIXServerEndpoint -> EventLoop.create_unix_server
  • t.i.e.UNIXClientEndpoint -> EventLoop.create_unix_connection
  • t.i.e.TCP4ServerEndpoint -> EventLoop.create_server
  • t.i.e.TCP4ClientEndpoint -> EventLoop.create_connection