Python Generator



Generators are way of implementing iterators. Generator function is a normal function except that it contains yield expression in the function definition making it a generator function. This function returns a generator iterator known as generator. To get the next value from a generator, we use the same built-in function as for iterators: next() . next() takes care of calling the generator's __next__() method.
When a generator function calls yield, the "state" of the generator function is frozen; the values of all variables are saved and the next line of code to be executed is recorded until next() is called again. Once it is, the generator function simply resumes where it left off. If next() is never called again, the state recorded during the yield call is (eventually) discarded.
Example of generators:
def gen_func_odd_nums():
    odd_num = 1
    while True:
        yield odd_num         # saves context and return from function
        odd_num = odd_num + 2

generator_obj = gen_func_odd_nums();
print "First 10 odd numbers:"
for i in range(10):
    print next(generator_obj) # calls generator_obj.__next__()

 
Output:

First 10 odd numbers:
1
3
5
7
9
11
13
15
17
19

No comments:

Post a Comment