Skip to content

Instantly share code, notes, and snippets.

@Laharah
Last active February 13, 2016 08:34
Show Gist options
  • Save Laharah/f3b45fb294fe39f1c405 to your computer and use it in GitHub Desktop.
Save Laharah/f3b45fb294fe39f1c405 to your computer and use it in GitHub Desktop.
convert a conventional generator into a coroutine
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]
@Laharah
Copy link
Author

Laharah commented Feb 13, 2016

small function to convert a generator into a coroutine. A bit niche, but useful in the right situation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment