[Twisted-Python] Consistent interfaces to asynchronous partially-available services using Deferreds and state machines (was Re: Another approach to allowing __init__ to work with Deferreds)

Phil Christensen phil at bubblehouse.org
Thu May 21 08:37:16 MDT 2009


On May 20, 2009, at 6:10 PM, Tristan Seligmann wrote:
> On Tue, May 12, 2009 at 1:39 PM, Terry Jones <terry at jon.es> wrote:
>> If Python allowed me to return a deferred from __init__, my problem  
>> would
>> vanish.  That's not going to happen though, I know :-)
>
> Well, if you /really/ want to, you can implement that; something like:
>
> ####
> from twisted.internet import defer
>
> class DeferredClass(object):
>    def __new__(cls, *a, **kw):
>        inst = super(DeferredClass, cls).__new__(cls, *a, **kw)
>        return defer.maybeDeferred(inst.__init__, *a,
> **kw).addCallback(lambda ign: inst)
> ####

That's a really succinct solution to the problem. I never even thought  
of using __new__ for this.

I'm inclined to say this is a better solution than the decorator-based  
one I sent along a few days ago, just because it's so simple. OTOH, my  
approach has one additional feature that I think is pretty nice, which  
is that you can call instance methods on the init-deferred object  
before the __init__ callback has been triggered, even if they need  
some of that initialized state (thus returning a Deferred).

-phil




More information about the Twisted-Python mailing list