Asynchronous code in a context manager

Peter Westlake <[email protected]>
Newsgroups gmane.comp.python.twisted
Message-ID <1521803817.3234826.1313425600.055CCD14@webmail.messagingengine.com>
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.

_______________________________________________
Twisted-Python mailing list
[email protected]
https://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.