[Twisted-Python] Another approach to allowing __init__ to work with Deferreds

Terry Jones terry.jones at gmail.com
Mon May 11 22:28:42 MDT 2009


Hi Drew. Thanks for the reply.

>>>>> "Drew" == Drew Smathers <drew.smathers at gmail.com> writes:

Drew> Somewhere, someplace something has to get a reference to the object
Drew> and it seems to me you're trying to prevent that something from
Drew> calling methods on the instance of the object before it's ready.  So
Drew> why not just defer providing the reference instead of wrapping
Drew> methods and intercepting calls?  To illustrate, here's a simple
Drew> modification of your example--assuming that `deferred' is an
Drew> attribute on Things set in __int__()--that would achieve this without
Drew> any special mixins:

Drew> def theThingThatGetsTheReference(t):
Drew>     d1 = t. f1(44)
[snip]
Drew> if __name__ == '__main__':
Drew> t = Thing()
Drew> t.deferred.addCallback(lambda ign: theThingThatGetTheReference(t))

I hadn't thought about doing it that way. It's in the first category of
approaches: making the instance available when the deferred fires. Several
approaches with the same flavor are in the original thread.  I agree your
way is simpler, but I like it less:

 - The class is now special, in the sense that a caller can't just treat it
   as a normal class and call its instance methods. You need to know this
   before using the class...

 - If you don't, it's nevertheless possible to call instance methods
   directly (without waiting on the deferred).  The solutions in the
   original thread did not allow this. They guaranteed that the deferred
   had fired via a metaclass, via using __new__, or via using a classmethod
   to call __init__.

 - It puts the extra work of getting a properly initialized instance onto
   the caller. This may seem like a trivial concern, but I'd rather my
   classes looked/behaved like regular Python classes if possible: i.e.,
   get an instance, immediately use it.

If I'd thought of your approach initially, I almost certainly would have
gone with it and not spent time trying to dream up more elaborate
solutions.  Thanks again for replying. It's good to get a reply at all,
and, as usual, I've learned something.

Terry




More information about the Twisted-Python mailing list