Chaining Events

Lately I've been dinking around with a wonderful library for Python called Twisted. Twisted is a networking library that makes creating custom clients and servers insanely easy.

Like a lot of good libraries Twisted starts off with a philosophy (think Ruby on Rails, etc) - in Twisted's case it's "You don't call Twisted, Twisted calls you". If that immediately makes you think "hey they must be doing some neat things with events!" then you're right.

When you're using Twisted and you call a function that needs to do some sort of work where it will takes some time for the result to be available you don't have to wait for that result to come. Instead the function immediately returns an instance of the Deferred class. What is the Deferred class you ask? Well, I think the Twisted manual explains it best:

Twisted uses the Deferred object to manage the callback sequence. The client application attaches a series of functions to the deferred to be called in order when the results of the asychronous request are available (this series of functions is known as a series of callbacks, or a callback chain), together with a series of functions to be called if there is an error in the asychronous request (known as a series of errbacks or an errback chain). The asychronous library code calls the first callback when the result is available, or the first errback when an error occurs, and the Deferred object then hands the results of each callback or errback function to the next function in the chain.

I happen to think that's a pretty neat take on chaining events and am seriously debating creating a similar system for a new little project I'm working on that will involve a lot of async programming.

In general finding this concept reminds me about why it's so important to go outside of your usual mental playground and find other places where developers are playing. Almost every time I do this and go look at something like Python or Objective C or Haskell I end up finding a concept I want to port over to one of my usual tools.