Skip to content

Instantly share code, notes, and snippets.

@ramalho
Created February 16, 2015 17:59
Show Gist options
  • Select an option

  • Save ramalho/c1f7df10308a4bd67198 to your computer and use it in GitHub Desktop.

Select an option

Save ramalho/c1f7df10308a4bd67198 to your computer and use it in GitHub Desktop.
A ``send`` function to drive coroutines
"""
A ``send`` function to drive coroutines.
Driving a coroutine that does not yield interesting values:
>>> coro_printer = printer()
>>> _ = send(coro_printer, 10)
got -> 10
>>> _ = send(coro_printer, 20)
got -> 20
In the case of ``printer``, the result of ``send`` can be ignored,
it will always be (None, None):
>>> send(coro_printer, 10)
got -> 10
(None, None)
Driving a coroutine that yields non-None values:
>>> coro_adder = adder()
>>> send(coro_adder, 10)
(0, 10)
You can always unpack the result, and ignore the first it it's not useful:
>>> _, total = send(coro_adder, 20)
>>> total
30
>>> _, total = send(coro_adder, 12)
>>> total
42
"""
import inspect
def send(generator, value):
if inspect.getgeneratorstate(generator) == 'GEN_CREATED':
first = next(generator)
else:
first = None
second = generator.send(value)
return (first, second)
### sample coroutines for demonstration
def printer():
"""Coroutine that does not yield interesting values"""
while True:
print('got ->', (yield))
def adder():
"""Coroutine that yields interesting values"""
total = 0
while True:
total += yield total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment