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

Drawing Sierpinski's Triangle in Minecraft Using Python

In his keynote at PyCon, Eben Upton, the Executive Director of the Rasberry Pi Foundation, mentioned that not only has Minecraft been ported to the Rasberry Pi, but you can even control it with Python . Since four of my kids are avid Minecraft fans, I figured this might be a good time to teach them to program using Python. So I started yesterday with the goal of programming something cool for Minecraft and then showing it off at the San Francisco Python Meetup in the evening. The first problem that I faced was that I didn't have a Rasberry Pi. You can't hack Minecraft by just installing the Minecraft client. Speaking of which, I didn't have the Minecraft client installed either ;) My kids always play it on their Nexus 7s. I found an open source Minecraft server called Bukkit that "provides the means to extend the popular Minecraft multiplayer server." Then I found a plugin called RaspberryJuice that implements a subset of the Minecraft Pi modding API for B

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

Creating Windows 10 Boot Media for a Lenovo Thinkpad T410 Using Only a Mac and a Linux Machine

TL;DR: Giovanni and I struggled trying to get Windows 10 installed on the Lenovo Thinkpad T410. We struggled a lot trying to create the installation media because we only had a Mac and a Linux machine to work with. Everytime we tried to boot the USB thumb drive, it just showed us a blinking cursor. At the end, we finally realized that Windows 10 wasn't supported on this laptop :-/ I've heard that it took Thomas Edison 100 tries to figure out the right material to use as a lightbulb filament. Well, I'm no Thomas Edison, but I thought it might be noteworthy to document our attempts at getting it to boot off a USB thumb drive: Download the ISO. Attempt 1: Use Etcher. Etcher says it doesn't work for Windows. Attempt 2: Use Boot Camp Assistant. It doesn't have that feature anymore. Attempt 3: Use Disk Utility on a Mac. Erase a USB thumb drive: Format: ExFAT Scheme: GUID Partition Map Mount the ISO. Copy everything from