How do I make a generator?

A very common question is whether to develop a “Hello World” generator or do it as a complete program.

For completeness, here is an example, written for Python 2.7, that makes a generator of the form

# Generator for the simple case import random def init_y_or_x(): for i in range(5): x, y = random.randint(0, len(x)+1) f = set() f.add(init_x) for i in range(5): g = random.get_randint(i+2, len(g)+3) for i in range(5): h = random.random() r = random.randint(0, f) gb = gb + r print_y(gb, h, init_x, init_y)

A program using this generator can be written like:

if __name__ == ‘__main__’ : init_y_or_x() # This works. print_y(init_x, init_y, generator=generator) # Print the first 3 numbers. if __name__ == ‘__main__’ : init_y_or_x() # This works, but prints some blank output. print_y(random.random(init_y_or_x), random.random(seed=random.random())))

Note that both the generator and the generated values are defined, so that you can use them together with a for loop in your program.

In fact, you can pass functions to the generator like:

for y in __main__.generate() for xx in __main__.generate()

This is one of the advantages of the module.

The last, but definitely not least, is its simple and easy to understand interface.

One problem with generators is that they’re often not needed very much because if you want to give an iterable or a tuple or a list you can do that quickly with an ordinary function. If the generator is used often then you must decide whether or not to extend it to be useful. If so, do it. If not, don’t. If you need the generator then don’t use it for this book… except in special cases.

If you use generators in your code you can tell the generator how to act (or not act) and where to be. For instance, suppose