Re:Callbacks as our Generation's Goto Statement
by rosh on Thursday August 15, 2013 @09:18PM
(#6221659)
Tornado has a similar interface:
class GenAsyncHandler(RequestHandler):
@gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch("http://example.com")
do_something_with_response(response)
self.render("template.html")
(via http://www.tornadoweb.org/en/stable/gen.html ..)
Re:Callbacks as our Generation's Goto Statement
by obiterdictum on Thursday August 15, 2013 @09:23PM
(#6221673)
Obligatory mention of gevent[1].
It handles all the plumbing for you with monkey-patching I/O calls. No annotations necessary, you just write linear code.
Re:Callbacks as our Generation's Goto Statement
by ak217 on Thursday August 15, 2013 @07:39PM
(#6221306)
Yes! I really hope this use of yield will bubble up to the language spec and become pervasive in Python. It really strikes me as the Pythonic approach to solving callback hell.
Re:Callbacks as our Generation's Goto Statement
by masklinn on Friday August 16, 2013 @03:41AM
(#6222680)
> Yes! I really hope this use of yield will bubble up to the language spec and become pervasive in Python.
And the time machine spaketh: http://www.python.org/dev/peps/pep-3156/#coroutines-and-the-...
(it has no reason to "bubble up to the language spec", the language provides all the right primitives — especially with Python 3's `yield from`, it's up to the libraries to use them. That is a Good Thing.)
Re:Callbacks as our Generation's Goto Statement
by ak217 on Friday August 16, 2013 @12:22PM
(#6224968)
Good point. Bubble up to the standard library, then.
Re:Callbacks as our Generation's Goto Statement
by danabramov on Thursday August 15, 2013 @07:22PM
(#6221228)
That's very cool, thanks for sharing.
There is work to make a similar async interface native in Python 3, in PEP 3156 http://www.python.org/dev/peps/pep-3156/, so this should become more widely available even to those who don't use Twisted.