Skip to content

Instantly share code, notes, and snippets.

@harrisont
Last active June 6, 2016 09:20
Show Gist options
  • Save harrisont/c7829e2c36235ad9ba3fb3d70d4963e9 to your computer and use it in GitHub Desktop.
Save harrisont/c7829e2c36235ad9ba3fb3d70d4963e9 to your computer and use it in GitHub Desktop.
Coroutine helpers and example
def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return start
@coroutine
def broadcast(*sinks):
try:
while True:
item = yield
for sink in sinks:
sink.send(item)
finally:
for sink in sinks:
sink.close()
def send_all(source, sink):
try:
for item in source:
sink.send(item)
finally:
sink.close()
@coroutine
def plus1(sink):
"""Adds 1 from the source and sends it to `sink`."""
try:
while True:
n = yield
sink.send(n + 1)
finally:
sink.close()
@coroutine
def printer():
while True:
n = yield
print(n)
def main():
values = [1, 2, 3]
sink = broadcast(
printer(),
plus1(printer()),
)
send_all(values, sink)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment