Skip to main content

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.

Comments

jjinux 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().
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.
jjinux 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.
jjinux 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.
jjinux 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!

Popular posts from this blog

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

ERNOS: Erlang Networked Operating System

I've been reading Dreaming in Code lately, and I really like it. If you're not a dreamer, you may safely skip the rest of this post ;) In Chapter 10, "Engineers and Artists", Alan Kay, John Backus, and Jaron Lanier really got me thinking. I've also been thinking a lot about Minix 3 , Erlang , and the original Lisp machine . The ideas are beginning to synthesize into something cohesive--more than just the sum of their parts. Now, I'm sure that many of these ideas have already been envisioned within Tunes.org , LLVM , Microsoft's Singularity project, or in some other place that I haven't managed to discover or fully read, but I'm going to blog them anyway. Rather than wax philosophical, let me just dump out some ideas: Start with Minix 3. It's a new microkernel, and it's meant for real use, unlike the original Minix. "This new OS is extremely small, with the part that runs in kernel mode under 4000 lines of executable code.&quo

Haskell or Erlang?

I've coded in both Erlang and Haskell. Erlang is practical, efficient, and useful. It's got a wonderful niche in the distributed world, and it has some real success stories such as CouchDB and jabber.org. Haskell is elegant and beautiful. It's been successful in various programming language competitions. I have some experience in both, but I'm thinking it's time to really commit to learning one of them on a professional level. They both have good books out now, and it's probably time I read one of those books cover to cover. My question is which? Back in 2000, Perl had established a real niche for systems administration, CGI, and text processing. The syntax wasn't exactly beautiful (unless you're into that sort of thing), but it was popular and mature. Python hadn't really become popular, nor did it really have a strong niche (at least as far as I could see). I went with Python because of its elegance, but since then, I've coded both p