Last active
February 13, 2016 08:34
-
-
Save Laharah/f3b45fb294fe39f1c405 to your computer and use it in GitHub Desktop.
convert a conventional generator into a coroutine
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
def coro_from_gen(generator): | |
"""turn a normal generator into a coroutine that can recieve and return computed data""" | |
def input_pipe(): | |
"""small internal coroutine that recieves data""" | |
x = '' | |
while True: | |
x = yield x | |
yield # to keep the generator in lock step with input | |
pipe = input_pipe() | |
next(pipe) # prime the input coroutune | |
gen = generator(pipe) | |
n = yield # get first item | |
while True: | |
pipe.send(n) | |
n = yield next(gen) | |
def test_coro_from_gen(): | |
"""trivial working example""" | |
def square(nums): | |
for n in nums: | |
yield n*n | |
coro = coro_from_gen(square) | |
next(coro) | |
results = [coro.send(x) for x in range(10)] | |
assert results == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
small function to convert a generator into a coroutine. A bit niche, but useful in the right situation.