Playing With Twisted and Deferreds And Returning Multiple Arguments

Twisted's Deferreds is a cool way of managing callbacks. You can return multiple arguments to the first callback but I wanted to return more than one result for the second function. It occurred to me I should use a tuple. Review the sample below:

    # example.py
from twisted.internet.defer import Deferred

    def myCallback(age, name, sex):
            age += 10
            print age, name, sex
            return (age, name)

    def trueGuy(res):
            print "My full name is", res[1]+' Appleton'
            print "My real age is", res[0]+10

    d = Deferred()
    d.addCallback(myCallback, name='Larry', sex='male')
    d.addCallback(trueGuy)
    d.callback(29)

This bit of code returns a tuple for the first callback. The tuple contains the age and name information for the second callback.

$ python example.py
39 Larry male
My full name is Larry Appleton
My real age is 49

This example works with a tuple. Later I will try and use a dictionary for the same result.

blogroll

social