[Twisted-Python] Converting async to sync code (blocking until deferreds fire)

Jack Whitham jack-tp at cs.york.ac.uk
Mon Jul 21 06:19:23 EDT 2008


What is the best way to convert asynchronous code (non-blocking,
returning deferreds) to synchronous code (blocking)? 

I have a client that is written using Twisted. Most of the methods
within the client object return Deferreds because they send messages
to a server and replies may take some time. This is ideal for the 
wxwidgets GUI that was originally intended to use the client. But
now I want to write test scripts for the server that are synchronous.

For example, the client provides the method "GetBitInfo" which returns
a deferred. The deferred is called back with a list as its parameter
after the server responds to a request. I would like to be able to 
do something like this:

> def GotBitInfo(l): pass
> if __name__ == "__main__":
>     c = Client()
>     d = c.GetBitInfo()
>     d.addCallback(GotBitInfo)
>     waitForDeferred(d)
>     d = c.DoSomethingElse()

In other words, how do I waitForDeferred(), i.e. block until a Deferred fires?

Of course I could rewrite my script as asynchronous code; but what I
really want is a simple Python-like interface for the client code
in order to make things as simple as possible for other users. I don't
want them to *have* to learn how to write asynchronous code - I want
it to be optional. If the snippet of code listed above is possible,
then I can wrap the client methods with code that waits for deferreds
to fire, then returns the values they were called with. Then the users
will have two ways to use the code: asynchronous (for GUIs, proxy
servers, etc.) and synchronous (for test scripts). 

I noticed that there is a _wait method in your trial code that seems to
do what I want, but it looks complicated and I'm not sure it is the
right answer. Its predecessor was also deprecated, which is a bad
sign (looks like "do not do this!!"). Hence I am looking for expert 


Jack Whitham
jack at cs.york.ac.uk

More information about the Twisted-Python mailing list