Created
September 15, 2018 19:24
-
-
Save dcoles/fdfd9db34e2c91d557056bfeb96212ad to your computer and use it in GitHub Desktop.
Coroutines in Python
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
"""Producer/Consumer coroutines.""" | |
import asyncio | |
q = asyncio.Queue(7) | |
def reader(iterable): | |
"""Producer.""" | |
it = iter(iterable) | |
while True: | |
while not q.full(): | |
# Create a new item | |
try: | |
value = next(it) | |
print(".") | |
except Exception as e: | |
value = e | |
# Add it to the queue | |
q.put_nowait(value) | |
# Yield to consumer | |
yield printer | |
def printer(): | |
"""Consumer.""" | |
while True: | |
while not q.empty(): | |
# Remove item from the queue | |
value = q.get_nowait() | |
if isinstance(value, Exception): | |
raise value | |
# Use item | |
print(value) | |
# Yield to producer | |
yield reader | |
if __name__ == "__main__": | |
d = dict() | |
d[reader] = reader(range(100)) | |
d[printer] = printer() | |
current = reader | |
while True: | |
try: | |
current = next(d[current]) | |
except StopIteration: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment