[Twisted-Python] Interview question on deferreds

Terry Jones terry at jon.es
Fri Mar 6 05:41:37 EST 2009

I'm going to post a few short comments on deferreds. As a fun standalone
warm-up exercise, here's an interview-style question for people who claim
to understand Twisted's deferreds.

What will the following code print, and why?

    from twisted.internet import defer

    def e_ok(x):
        print 'extra is ok:', x
        return x

    def e_nok(f):
        # Propagate the failure (by returning it).
        print 'extra failed'
        return f

    def raiser(_):
        raise Exception('oops')

    extra = defer.Deferred()
    extra.addCallbacks(e_ok, e_nok)
    extra.addCallbacks(e_ok, e_nok)

    def d_nothing(x):
        print 'Doing nothing with:', x
        return x

    def d_ok(x):
        print 'd is ok:', x

    def d_nok(f):
        # Absorb the failure (by implicitly returning None).
        print 'd failed'

    d = defer.Deferred()
    d.addCallbacks(d_ok, d_nok)


Don't read my next post if you prefer to figure this out yourself.


More information about the Twisted-Python mailing list