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

Terry Jones terry at jon.es
Mon Nov 3 08:11:05 EST 2008

>>>>> "Esteve" == Esteve Fernandez <esteve at sindominio.net> writes:
Esteve> I'm going to jump in. How about this:

That's nice. But you've coupled the args to aFuncReturningADeferred and
what it's Deferred ends up returning to the args for __init__ of the class.
I think you meant 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, *args, **kw):
            def cb(x):
                obj = object.__new__(cls)
                obj.__init__(*args, **kw)
                return obj
            return aFuncReturningADeferred("Some value").addCallback(cb)

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

    def printFoo(obj):
        print obj.value

    d = Foo("Some other value")

I.e., __new__ can do whatever it likes with preparing args for
aFuncReturningADeferred (including using args and kw), and all of the args
to __new__ are passed to __init__, as the caller would expect from a normal
class. You're passing the return result of the Deferred as the single arg
to __init__.

Anyway, I like it more than my solution.


More information about the Twisted-Python mailing list