Generator function

The generator function is a special function into Python language. It is a function that do not terminate after returning a result. Instead it’s instance is preserved in memory for a while until the last result is created. Think about it like a resumable function.

Example:

#Create a generator
def test_generator(p_stop):
    counter = 0
    while counter <= p_stop:
       yield counter
       counter +=1

def main():
    # example generator:"aindex"
    print("call generator using loop")
    aindex = test_generator(3)
    for i in aindex:
        print("i=%d" % i)
        
    # example generator:"bindex"     
    print("call generator using next")
    bindex = test_generator(3)
    print("y=%d" % next(bindex))
    print("y=%d" % next(bindex))

# compiler entry point
if __name__ == "__main__":
    main()

This will print:

call generator using loop
i=0
i=1
i=2
i=3
call generator using next
y=0
y=1

test_generator

The function generator is test_generator(). This is a resumable function that will stay in memory and wait for next() to be invoked. When the last element is generated the function terminate. A generator function is a “high order function” and must be instantiated with a parameter.

aindex

I have created 2 generators using the same function. First generator “aindex” is used into a loop like an iterable collection. Not all values are generated in memory but one by one. This is very efficient.

bindex

Second generator bindex = test_generator(3).For this generator I have used next(bindex) to create 2 values (0, 1). Evert time next() is invoked a new value is created. The third value is never used therefore “bindex” generator do not reach the end until program termination.

Keyword yield

Keyword yield is specific to generators. This is like return, except the function do not terminate. Instead the execution is suspended and resumed using next(). This construct is very common in Python and is used for performance.

Read next: Classes