[Twisted-Python] Asynchronous code in a context manager
![](https://secure.gravatar.com/avatar/e0114f22fcde3deed8ebe94c70652140.jpg?s=120&d=mm&r=g)
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.
![](https://secure.gravatar.com/avatar/a93db92c60e9d5435d204407264457f2.jpg?s=120&d=mm&r=g)
Are you using Python3? Then there's "asynchronous context managers". I finally found a use-case for one in txtorcon, so here's an example: http://txtorcon.readthedocs.io/en/latest/txtorcon-controller.html#txtorcon.T... -- meejah
![](https://secure.gravatar.com/avatar/a93db92c60e9d5435d204407264457f2.jpg?s=120&d=mm&r=g)
Are you using Python3? Then there's "asynchronous context managers". I finally found a use-case for one in txtorcon, so here's an example: http://txtorcon.readthedocs.io/en/latest/txtorcon-controller.html#txtorcon.T... -- meejah
participants (2)
-
meejah
-
Peter Westlake