[Twisted-Python] Asynchronous code in a context manager

Peter Westlake peter.westlake at pobox.com
Fri Mar 23 05:16:57 MDT 2018


I have a context manager whose __exit__ method needs to run some asynchronous Twisted code. Using Crochet's @wait_for very nearly works:

no_setup()

class Example(object):
    def __exit__(t, v, tb):
            return self.cleanup()

   @wait_for
   @inlineCallbacks
    def cleanup(self):
           yield .....
           returnValue(False)

    ....

Then
     with e as Example():

This gets an error because the cleanup function is being called in the reactor thread. Using reactor.callInThread(self.cleanup()) makes it work up to a point, but it doesn't wait for the thread to finish. Is there a way to make this work? The alternative is simply to call the cleanup function explicitly from the with statement, and have the __exit__ handler throw an error if you forget. So any solution needs to be cleaner than that, or there's no point. I'm beginning to suspect that this is the case!

Peter.



More information about the Twisted-Python mailing list