Friday, January 07, 2011

Python: use_twisted Decorator

This is a decorator that you can put on a Python function that will temporarily fire up Twisted's reactor and run a function under Twisted. This is useful if most of your program doesn't use Twisted, but you have a function that must use Twisted.

Here's an example of using it:
@use_twisted
@defer.inlineCallbacks
def do_something_twisted():
value = yield do_something_else_twisted()
other_value = yield do_more_stuff()
defer.returnValue(value + other_value)
Here's the decorator:
def use_twisted(twisted_function):

"""This is a decorator to run a function under Twisted.

Temporarily fire up the reactor and run the function under Twisted.
It should return a deferred, of course.

Unfortunately, there's a bug in Twisted that only allows you to
start and stop the reactor once. See
http://jjinux.blogspot.com/2011/01/python-usetwisted-decorator.html.
Hence, this decorator will prevent you from calling it twice. So
sorry :(

"""

from twisted.python.failure import Failure

captured_value = [] # Think of this as a box.

def wrapper(*args, **kargs):
reactor.callLater(0, call_twisted_function, twisted_function, args,
kargs)
reactor.run()
assert captured_value
value = captured_value[0]
if isinstance(value, (Exception, Failure)):
raise value
else:
return value

def call_twisted_function(twisted_function, args, kargs):
deferred = twisted_function(*args, **kargs)
deferred.addBoth(capture_and_stop)

def capture_and_stop(value):
captured_value.append(value)
reactor.callLater(0, reactor.stop)
return value

if globals().get("_reactor_run", False):
raise AssertionError("The use_twisted decorator can only be used once")
else:
globals()["_reactor_run"] = True

return wrapper
Updated: Added code to prevent the decorator from being called twice.

7 comments:

Shannon -jj Behrens said...

This function works perfectly well, but there's just one problem. There's a bug in Twisted that only lets you start the reactor once. See: http://markmail.org/message/w4tmetzgmuepshcl. Hence, you can only use this decorator once. If you try to use it twice, it'll run, and it'll even call reactor.stop(), but it'll never return from reactor.run().

Jean-Paul Calderone said...

It's not a bug. It's a feature.

glyph said...

Starting the reactor means starting your program. If you need to 'temporarily' start the reactor, then your program is almost certainly full of weird potential reentrancy bugs, and your code will fail when the context of its execution changes in the slightest. This is bad, bad, bad.

Since we don't like Twisted being blamed for these kinds of crazy, impossible-to-debug scenarios where all of your sockets appear to be going haywire, we don't have a lot of incentive to "fix" the issue that reactors can't be restarted. (To be clear: this is not an issue with Twisted, it's just what happens when you start mixing asynchronous stream I/O with reentrant main loops.)

A more pressing bug is eliminating all usage of reactor.run() from our example code, and replacing it with a tool that can run a script in a context where the reactor is already running (like twistd, but simpler) so that new developers won't think that they're supposed to call it for every little thing.

Anonymous said...

you could use a greenlet to start the twisted reactor and switch to the "twisted greenlet" in order to run a function under twisted's control. this way you can start multiple functions.

Shannon -jj Behrens said...

> It's not a bug. It's a feature.

It's not a feature when you call reactor.stop() once and it works, but when you call it a second time, it gets hung in an infinite loop. If a nice exception were raised, I'd call it a feature.

Shannon -jj Behrens said...

> Starting the reactor means starting your program. If you need to 'temporarily' start the reactor, then your program is almost certainly full of weird potential reentrancy bugs, and your code will fail when the context of its execution changes in the slightest. This is bad, bad, bad.

Hey, glyph ;)

I like to think I know what I'm doing, and that I'm not a mere clueless newbie. I need to use Twisted to look up some account data. I'm using a company library that requires Twisted. Once I get the data, I can completely exit Twisted and run in a completely synchronous manner. That's all working fine. I thought I could re-enter Twisted and exit properly (which in theory should work perfectly well), but it didn't work.

If you really, really don't want people starting and stopping the reactor twice, you should raise an exception when they try to do it. However, I see no reason why that should be the case. An expert user can enter and exit the reactor in the same way an expert user can mix Twisted with threads when necessary.

Shannon -jj Behrens said...

> you could use a greenlet to start the twisted reactor and switch to the "twisted greenlet" in order to run a function under twisted's control. this way you can start multiple functions.

Yeah, that's what I had in mind too. Thanks!