Skip to content

Instantly share code, notes, and snippets.

@thomie
Last active December 15, 2015 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomie/5321742 to your computer and use it in GitHub Desktop.
Save thomie/5321742 to your computer and use it in GitHub Desktop.
Coroutines in Python
# Simple Generators
# http://www.python.org/dev/peps/pep-0255/
def producer():
a, b = 0, 1
while True:
a, b = b, a + b
yield a
def pull():
p = producer()
for _ in range(10):
a = p.next() # pull
print a
pull()
# Coroutines via Enhanced Generators
# http://www.python.org/dev/peps/pep-0342/
def push():
c = consumer()
c.next()
a, b = 0, 1
for _ in range(10):
a, b = b, a + b
c.send(a) # push
def consumer():
while True:
a = yield
print a
push()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment