4 ms·
You get a similar interface in Python's Twisted using the @inlineCallbacks decorator: @inlineCallbacks def example(): try: obtain_s
by lambda 13y ago
You get a similar interface in Python's Twisted using the @inlineCallbacks decorator:
@inlineCallbacks
def example():
try:
obtain_some_lock()
ui_status("Fetching file...")
result = yield fetch_file_from_server(args)
ui_status("Uploading file...")
yield post_file_to_other_server(result)
ui_status("Done.")
except SomeError as e:
ui_status("Error: %s" % e.msg)
finally:
release_some_lock()
I must say that this style of writing async code is much friendlier than descending into callback hell.
There is work to make a similar async interface native in Python 3, in PEP 3156 http://www.python.org/dev/peps/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.
- danabramov 13y agoThat's very cool, thanks for sharing.
- ak217 13y agoYes! 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.
- masklinn 13y ago> 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-scheduler 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.)
- ak217 13y agoGood point. Bubble up to the standard library, then.
- rosh 13y agoTornado 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 http://www.tornadoweb.org/en/stable/gen.html ..)
- obiterdictum 13y agoObligatory 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. [1] http://www.gevent.org http://www.gevent.org