Last active
June 6, 2016 09:20
-
-
Save harrisont/c7829e2c36235ad9ba3fb3d70d4963e9 to your computer and use it in GitHub Desktop.
Coroutine helpers and example
This file contains hidden or 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 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() |
This file contains hidden or 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
@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