Skip to content

Instantly share code, notes, and snippets.

@yyuu
Created December 1, 2011 07:21
Show Gist options
  • Save yyuu/1414604 to your computer and use it in GitHub Desktop.
Save yyuu/1414604 to your computer and use it in GitHub Desktop.
a coroutine implementation that can work with tornado.ioloop
#!/usr/bin/env python
import tornado.ioloop
class Coroutine(object):
"""
a coroutine implementation that can work with tornado.ioloop
def generator():
print('A')
yield
print('B')
def finished():
print('Z')
co = Coroutine(generator)
co(finished)
--
A
B
Z
"""
def __init__(self, generator, io_loop=None):
self.generator = generator
self.iterator = None
self.io_loop = tornado.ioloop.IOLoop.instance() if io_loop is None else io_loop
self.alive = True
def __call__(self, *args):
try:
if self.iterator is None:
self.iterator = self.generator(*args)
response = next(self.iterator)
else:
if 0 < len(args):
response = self.iterator.send(*args)
else:
response = next(self.iterator)
self.io_loop.add_callback(self)
except StopIteration:
self.alive = False
# vim:set ft=python :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment