[Twisted-Python] Synchronous @inlineCallback interpreter

Clayton Daley clayton.daley at gmail.com
Thu Apr 24 17:45:03 MDT 2014


I have a modular application that communicates over RPC connections (with
both sync and async server/clients available).  I want to migrate some of
the modules over to Twisted. Currently, all modules inherit important
utility functions from a parent class.  On paper, I now need two versions
of this parent class (synchronous & asynchronous) to be inherited by
modules of the respective types.

I'm looking for ways to maximize the common code between the two versions
of the parent object. One that comes to mind (motivating the subject of
this post) would be to write a synchronous interpreter for @inlineCallback
calls.  For example, here's a synchronous factory function from the parent
class (already partly reconfigured to be friendly to my idea):

    @classmethod
    def from_id(cls, id):
        doc = db.get_document(id) # blocking db call
        self = cls._new_document(doc) # synchronous initialization stuff
        self.__init__() # module init code is custom and may block
        return self

I imagine rewriting this to the following:

    @classmethod
    @inlineCallbacks
    def from_id(cls, id):
        doc = yield db.get_document(id) # blocking/async db call
        self = cls._new_document(doc) # always synchronous
        yield self.__init__() # blocking/async call
        returnValue(self)

Assuming the db connector and init function are appropriate to the
environment, my gut reaction is that this could (when combined with a
synchronous implementation of the decorator) run correctly in both places.
I've read that the @inlineCallback code is complicated so I figured I'd run
the idea by the experts before diving down that rabbit hole. Does anyone
see any obvious pitfall? I'm happy to do the legwork to try and build it,
but I'd also welcome any pointers from your (no doubt extensive) experience
writing the twisted version.

Thanks in advance!

Clayton Daley
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://twistedmatrix.com/pipermail/twisted-python/attachments/20140424/f5ec2261/attachment-0001.html>


More information about the Twisted-Python mailing list