state of execution is suspended and local variables are preserved. On the next call to the generator’s$_{__next__()}$ method, the function will resume executing. Here’s a sample usage of the$_{generate_ints()}$ generator: >>> gen =generate_ints( 3) >>> gen <generator object generate_ints at ...> >>> next(gen) 0 >>> next(gen) 1 >>> next(gen) 2 >>> next(gen) Traceback (most recent call last): File "stdin" , line1, in <module> File "stdin" , line2, in generate_ints StopIteration You could equally write for i in generate_ints(5) , or a, b, c = generate_ints(3) . Inside a generator function, return value causes StopIteration(value) to be raised from the __next__() method. Once this happens, or the bottom of the function is reached, the procession of values ends and the generator cannot yield any further values. You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables. For example, returning a list of integers could be done by setting$_{self.count}$ to 0, and having the$_{__next__()}$ method increment$_{self.count}$ and return it. However, for a moderately complicated generator, writing a corresponding class can be much messier. The test suite included with Python’s library, Lib/test/test_generators.py, contains a number of more interesting ex- amples. Here’s one generator that implements an in-order traversal of a tree using generators recursively. Two other examples in$_{test_generators.py}$ produce solutions for the N-Queens problem (placing N queens on an NxN chess board so that no queen threatens another) and the Knight’s Tour (finding a route that takes a knight to every square of an NxN chessboard without visiting any square twice). In Python 2.4 and earlier, generators only produced output. Once a generator’s code was invoked to create an iterator, there was no way to pass any new information into the function when its execution is resumed. You could hack together this ability by making the generator look at a global variable or by passing in some mutable object that callers then modify, but these approaches are messy. In Python 2.5 there’s a simple way to pass values into a generator. $_{yield}$became an expression, returning a value that can be assigned to a variable or otherwise operated on: val=( yield i) 4.1 Passing values into a generator # A recursive generator that generates Tree leaves in in-order. def inorder (t): if t: for x in inorder(t.left): yield x yield t.label for x in inorder(t.right): yield x 8