Skip to content

Instantly share code, notes, and snippets.

@jorge-lavin
Created August 26, 2014 10:27
Show Gist options
  • Save jorge-lavin/3b8314d3801f9d32ff92 to your computer and use it in GitHub Desktop.
Save jorge-lavin/3b8314d3801f9d32ff92 to your computer and use it in GitHub Desktop.
"""
Taken from http://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/
Just added a python2 check
"""
import sys
if sys.version[0] == '2':
print('This code is not Python 2 compliant exiting ...')
exit(0)
import random
def get_data():
"""Return 3 random integers between 0 and 9"""
return random.sample(range(10), 3)
def consume():
"""Displays a running average across lists of integers sent to it"""
running_sum = 0
data_items_seen = 0
while True:
data = yield
data_items_seen += len(data)
running_sum += sum(data)
print('The running average is {}'.format(running_sum / float(data_items_seen)))
def produce(consumer):
"""Produces a set of values and forwards them to the pre-defined consumer
function"""
while True:
data = get_data()
print('Produced {}'.format(data))
consumer.send(data)
yield
if __name__ == '__main__':
consumer = consume()
consumer.send(None)
producer = produce(consumer)
for _ in range(10):
print('Producing...')
next(producer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment