Tuesday, October 20, 2009

Twisted Application Reactors

At the heart of any Twisted Python application lies one or more reactors. Reactors, as the name suggests, react to events. Whether the event is local or remote, the reactor is the core concept in Twisted concerned with invoking behavior in response to these events.

The Twisted application module defines an application Reactor class. This class is extended by actual reactor implementations that may be used within Twisted applications. Reactors that are available for installation may be enumerated over by using the getReactorTypes() function. The use of this function is illustrated below.
#Example; Enumerating reactor types.

#Import the required function.
from twisted.application.reactors import getReactorTypes

if __name__=="__main__":

#Iterate over the reactor types.
for i in getReactorTypes():

#Display reactor information.
print i.shortName
print i.description,"\n"
The design of the Reactor class is really straightforward. The Reactor is an extensibility mechanism of the Twisted framework. That is, it can be installed and used as necessary. The Reactor class provides the IPlugin and the IReactorInstaller interfaces. The Reactor class and the interfaces it provides are illustrated below.
As you can see, the Reactor class has three simple attributes; shortName, moduleName, and description. The moduleName is really important for installing the reactor. It tells Twisted where the actual code for the reactor can be found.

The getReactorTypes() is useful for providing choices to the user. This would actually make more sense as a configuration option for advanced users such as an administrator.