def simple_generator_function():
""" a function becomes a 'generator' if it uses the yield keyword
the next time the function is called it resumes state from where it last yielded
"""
yield 1
yield 2
yield 3
# return 4 # don't use return with an argument inside a generator
def double( number ):
return 2 * number
def my_generator():
print (yield) + 10, # when called with .send() accepts input
print 11
print (yield) + 10,
print 11
if __name__ == '__main__':
our_generator = simple_generator_function()
print "manually call next: ", next( our_generator )
print "manually call next: ", next( our_generator )
g = my_generator()
g.send( None ) # to seed the generator
g.send( 1 ) # this will both send a value to the generator and then run until the next yield
# g.send( 2 ) # if this is called we finish the iterator and will receive a StopIteration Exception
print "for loop with a generator"
for value in simple_generator_function(): # generator functions can be used like an iterator
print value
doubles = map( double , simple_generator_function() )
print "used a map with a generator: ", type( doubles ), doubles # <type 'list'> [2, 4, 6]
print "manually call next (when nothing is left) gets an exception: ", next( our_generator )
print "manually call next (when nothing is left) gets an exception: ", next( our_generator )
# TODO: # print simple_generator_function.send( 4 )
# Join via a pipe an inputstream and an outputstream
# io.BufferedRWPair( reader, writer, buffer_size=DEFAULT_BUFFER_SIZE )