Part 3: Our Eye-beams Begin to Twist
Doing Nothing, the Twisted Way
Eventually we are going to re-implement our asynchronous poetry client using Twisted. But first let’s write a few really simple Twisted programs just to get the flavor of things. As I mentioned in Part 2, I developed these examples using Twisted 8.2.0. Twisted APIs do change, but the core APIs we are going to use will likely change slowly, if at all, so I expect these examples to work for many future releases. If you don’t have Twisted installed you can obtain it here.
The absolute simplest Twisted program is listed below, and is also available in basic-twisted/simple.py in the base directory of the twisted-intro example code.
from twisted.internet import reactor reactor.run()
You can run it like this:
As we saw in Part 2, Twisted is an implementation of the Reactor Pattern and thus contains an object that represents the reactor, or event loop, that is the heart of any Twisted program. The first line of our program imports the reactor object so we can use it, and the second line tells the reactor to start running the loop.
This program just sits there doing nothing. You’ll have to stop it by pressing Control-C, otherwise it will just sit there forever. Normally we would have given the loop one or more file descriptors (connected to, say, a poetry server) that we want to monitor for I/O. We’ll see how to do that later, but for now our reactor loop is stuck. Note that this is not a busy loop which keeps cycling over and over. If you happen to have a CPU meter on your screen, you won’t see any spikes caused by this technically infinite loop. In fact, our program isn’t using any CPU at all. Instead, the reactor is stuck at the top cycle of Figure 5, waiting for an event that will never come (to be specific, waiting on a
select call with no file descriptors).
That might make for a compelling metaphor of Hamletian inaction, but it’s still a pretty boring program. We’re about to make it more interesting, but we can already draw a few conclusions:
- Twisted’s reactor loop doesn’t start until told to. You start it by calling
- The reactor loop runs in the same thread it was started in. In this case, it runs in the main (and only) thread.
- Once the loop starts up, it just keeps going. The reactor is now “in control” of the program (or the specific thread it was started in).
- If it doesn’t have anything to do, the reactor loop does not consume CPU.
- The reactor isn’t created explicitly, just imported.
That last point is worth elaborating on. In Twisted, the reactor is basically a Singleton. There is only one reactor object and it is created implicitly when you import it. If you open the
reactor module in the
twisted.internet package you will find very little code. The actual implementation resides in other files (see, for example,
Twisted actually contains multiple reactor implementations. As mentioned in Part 2, the
select call is just one method of waiting on file descriptors. Twisted includes several reactor implementations that use a variety of different methods. For example,
twisted.internet.pollreactor uses the
poll system call instead of
To use a specific reactor, you must
install it before importing
twisted.internet.reactor. Here is how you install the
from twisted.internet import pollreactor pollreactor.install()
If you import
twisted.internet.reactor without first installing a specific reactor implementation, then Twisted will install the default reactor for you. The particular one you get will depend on the operating system and Twisted version you are using. For that reason, it is general practice not to import the reactor at the top level of modules to avoid accidentally installing the default reactor. Instead, import the reactor in the same scope in which you use it.
Note: as of this writing, Twisted has been moving gradually towards an architecture which would allow multiple reactors to co-exist. In this scheme, a reactor object would be passed around as a reference rather than imported from a module.
Note: not all operating systems support the
poll call. If that is the case for your system, this example will not work.
Now we can re-implement our first Twisted program using the
pollreactor, as found in basic-twisted/simple-poll.py:
from twisted.internet import pollreactor pollreactor.install() from twisted.internet import reactor reactor.run()
And we have a poll loop that does nothing at all instead of a select loop that does nothing at all. Neato.
We’re going to stick with the default reactor for the rest of this introduction. For the purposes of learning Twisted, all the reactors do the same thing.
Let’s make a Twisted program that at least does something. Here’s one that prints a message to the terminal window, after the reactor loop starts up:
def hello(): print 'Hello from the reactor loop!' print 'Lately I feel like I\'m stuck in a rut.' from twisted.internet import reactor reactor.callWhenRunning(hello) print 'Starting the reactor.' reactor.run()
This program is in basic-twisted/hello.py. If you run it, you will see this output:
Starting the reactor. Hello from the reactor loop! Lately I feel like I'm stuck in a rut.
You’ll still have to kill the program yourself, since it gets stuck again after printing those lines.
hello function is called after the reactor starts running. That means it is called by the reactor itself, so Twisted code must be calling our function. We arrange for this to happen by invoking the reactor method
callWhenRunning with a reference to the function we want Twisted to call. And, of course, we have to do that before we start the reactor.
We use the term callback to describe the reference to the
hello function. A callback is a function reference that we give to Twisted (or any other framework) that Twisted will use to “call us back” at the appropriate time, in this case right after the reactor loop starts up. Since Twisted’s loop is separate from our code, most interactions between the reactor core and our business logic will begin with a callback to a function we gave to Twisted using various APIs.
We can see how Twisted is calling our code using this program:
import traceback def stack(): print 'The python stack:' traceback.print_stack() from twisted.internet import reactor reactor.callWhenRunning(stack) reactor.run()
You can find it in basic-twisted/stack.py and it prints out something like this:
The python stack: ... reactor.run() <-- This is where we called the reactor ... ... <-- A bunch of Twisted function calls ... traceback.print_stack() <-- The second line in the stack function
Don’t worry about all the Twisted calls in between. Just notice the relationship between the
reactor.run() call and our callback.
What’s the deal with callbacks?
Twisted is not the only reactor framework that uses callbacks. The older asynchronous Python frameworks Medusa and asyncore also use them. As do the GUI toolkits GTK and QT, both based, like many GUI frameworks, on a reactor loop.
The developers of reactive systems sure love callbacks. Maybe they should just marry them. Maybe they already did. But consider this:
- The reactor pattern is single-threaded.
- A reactive framework like Twisted implements the reactor loop so our code doesn’t have to.
- Our code still needs to get called to implement our business logic.
- Since it is “in control” of the single thread, the reactor loop will have to call our code.
- The reactor can’t know in advance which part of our code needs to be called.
In this situation callbacks are not just one option — they are the only real game in town.
Figure 6 illustrates some important properties of callbacks:
- Our callback code runs in the same thread as the Twisted loop.
- When our callbacks are running, the Twisted loop is not running.
- And vice versa.
- The reactor loop resumes when our callback returns.
During a callback, the Twisted loop is effectively “blocked” on our code. So we should make sure our callback code doesn’t waste any time. In particular, we should avoid making blocking I/O calls in our callbacks. Otherwise, we would be defeating the whole point of using the reactor pattern in the first place. Twisted will not take any special precautions to prevent our code from blocking, we just have to make sure not to do it. As we will eventually see, for the common case of network I/O we don’t have to worry about it as we let Twisted do the asynchronous communication for us.
Other examples of potentially blocking operations include reading or writing from a non-socket file descriptor (like a pipe) or waiting for a subprocess to finish. Exactly how you switch from blocking to non-blocking operations is specific to what you are doing, but there is often a Twisted API that will help you do it. Note that many standard Python functions have no way to switch to a non-blocking mode. For example, the
os.system function will always block until the subprocess is finished. That’s just how it works. So when using Twisted, you will have to eschew
os.system in favor of the Twisted API for launching subprocesses.
It turns out you can tell the Twisted reactor to stop running by using the reactor’s
stop method. But once stopped the reactor cannot be restarted, so it’s generally something you do only when your program needs to exit.
Note: there has been past discussion on the Twisted mailing list about making the reactor “restartable” so it could be started and stopped as you like. But as of version 8.2.0, you can only start (and thus stop) the reactor once.
Here’s a program, listed in basic-twisted/countdown.py, which stops the reactor after a 5 second countdown:
class Countdown(object): counter = 5 def count(self): if self.counter == 0: reactor.stop() else: print self.counter, '...' self.counter -= 1 reactor.callLater(1, self.count) from twisted.internet import reactor reactor.callWhenRunning(Countdown().count) print 'Start!' reactor.run() print 'Stop!'
This program uses the
callLater API to register a callback with Twisted. With
callLater the callback is the second argument and the first argument is the number of seconds in the future you would like your callback to run. You can use a floating point number to specify a fractional number of seconds, too.
So how does Twisted arrange to execute the callback at the right time? Since this program doesn’t listen on any file descriptors, why doesn’t it get stuck in the
select loop like the others? The
select call, and the others like it, also accepts an optional timeout value. If a timeout value is supplied and no file descriptors have become ready for I/O within the specified time then the
select call will return anyway. Incidentally, by passing a timeout value of zero you can quickly check (or “poll”) a set of file descriptors without blocking at all.
You can think of a timeout as another kind of event the event loop of Figure 5 is waiting for. And Twisted uses timeouts to make sure any “timed callbacks” registered with
callLater get called at the right time. Or rather, at approximately the right time. If another callback takes a really long time to execute, a timed callback may be delayed past its schedule. Twisted’s
callLater mechanism cannot provide the sort of guarantees required in a hard real-time system.
Here is the output of our countdown program:
Start! 5 ... 4 ... 3 ... 2 ... 1 ... Stop!
Note the “Stop!” line at the ends shows us that when the reactor exits, the
reactor.run call returns. And we have a program that stops all by itself.
Take That, Twisted
Since Twisted often ends up calling our code in the form of callbacks, you might wonder what happens when a callback raises an exception. Let’s try it out. The program in basic-twisted/exception.py raises an exception in one callback, but behaves normally in another:
def falldown(): raise Exception('I fall down.') def upagain(): print 'But I get up again.' reactor.stop() from twisted.internet import reactor reactor.callWhenRunning(falldown) reactor.callWhenRunning(upagain) print 'Starting the reactor.' reactor.run()
When you run it at the command line, you will see this output:
Starting the reactor. Traceback (most recent call last): ... # I removed most of the traceback exceptions.Exception: I fall down. But I get up again.
Notice the second callback runs after the first, even though we see the traceback from the exception the first raised. And if you comment out the
reactor.stop() call, the program will just keep running forever. So the reactor will keep going even when our callbacks fail (though it will report the exception).
Network servers generally need to be pretty robust pieces of software. They’re not supposed to crash whenever any random bug shows its head. That’s not to say we should be lackadaisical when it comes to handling our own errors, but it’s nice to know Twisted has our back.
Now we’re ready to grab some poetry with Twisted. In Part 4, we will implement a Twisted version of our asynchronous poetry client.
- Update the countdown.py program to have three independently running counters going at different rates. Stop the reactor when all counters have finished.
- Consider the
LoopingCallclass in twisted.internet.task. Rewrite the countdown program above to use
LoopingCall. You only need the
stopmethods and you don’t need to use the “deferred” return value in any way. We’ll learn what a “deferred” value is in a later Part.