[Twisted-Python] A Python metaclass for Twisted allowing __init__ to return a Deferred

Esteve Fernandez esteve at sindominio.net
Mon Nov 3 05:20:25 EST 2008

On Monday 03 November 2008 00:48:20 Terry Jones wrote:
> I just posted a blog article with title as above: http://bit.ly/1whZUK

I'm going to jump in. How about this:

from twisted.internet import defer, reactor

def aFuncReturningADeferred(value):
    d = defer.Deferred()
    reactor.callLater(5, d.callback, value[::-1])
    return d

class Foo(object):

    def __new__(cls, value):
        def cb(x):
            obj = object.__new__(cls, x)
            return obj
        return aFuncReturningADeferred(value).addCallback(cb)

    def __init__(self, value):
        self.value = value

def printFoo(obj):
    print obj.value

d = Foo("Some value")


Instead of returning a deferred from the __init__ method (which is 
non-standard), you return it from __new__

It's clearer, since __init__ is meant for configuring instances, and __new__ 
for instantiating objects.


More information about the Twisted-Python mailing list