Skip to content

Instantly share code, notes, and snippets.

@dcoles
Created September 15, 2018 19:24
Show Gist options
  • Save dcoles/fdfd9db34e2c91d557056bfeb96212ad to your computer and use it in GitHub Desktop.
Save dcoles/fdfd9db34e2c91d557056bfeb96212ad to your computer and use it in GitHub Desktop.
Coroutines in Python
"""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