Skip to content

Instantly share code, notes, and snippets.

@jablko
Created January 26, 2011 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jablko/797019 to your computer and use it in GitHub Desktop.
Save jablko/797019 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import functools
# Take a generator function (i.e. a callable which returns a generator) and
# return a callable which calls .send()
class coroutine:
def __init__(self, function):
self.function = function
functools.update_wrapper(self, function)
def __call__(self, *args, **kwds):
try:
return self.generator.send(args)
except AttributeError:
self.generator = self.function(*args, **kwds)
return self.generator.next()
# Each time we're called, advance to next yield
@coroutine
def test():
yield 'call me once'
yield 'call me twice'
# Works like a charm : )
assert 'call me once' == test()
assert 'call me twice' == test()
class Test:
# Each time we're called, advance to next yield
@coroutine
def test(self):
yield 'call me once'
yield 'call me twice'
test = Test()
# TypeError, WTF?
assert 'call me once' == test.test()
assert 'call me twice' == test.test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment