Created
January 26, 2011 17:05
-
-
Save jablko/797019 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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