Or press ESC to close.

Generators

Dec 6 2021 4 min read

Generators

Topic on generators. Use case, wherever memory efficiency is most important. Simple generator is a function that has the 'yield' keyword in its scope. Usage is simple - first call the function to remember parameters sent in && use 'next' to iterate the elements, next in queue.

Example: Say you want to generate Fibonacci series which will provide the next number in the series, only when it is asked for. This is done by using 'next' builtin function.

                            
                                def fibgenerator(firstSeedNum, secondSeedNum):
                                while True:
                                    temp = firstSeedNum + secondSeedNum
                                    yield temp  # this statement suspends the function execution, until 'next' is called again
                                    firstSeedNum  = secondSeedNum
                                    secondSeedNum = temp
    
                                # two step process, create a generator object and iterate over the returned generator object. Creating generator
    
                                a = fibgenerator(0, 1) # this creates a generator object, that can be iterated to get the next element
                                # the above statement just packed the arguments and keep it ready for iteration
                                b = fibgenerator(3, 27) # this creates another generator object, with different initial seed numbers
                                for i in range(10):
                                print(next(a)) # this is a generator that will generate elements infinitely, since, there is a while loop, that's always true
                                            # when the next is called for the first time, temp is intermittently returned with function execution suspension
                                            # only when the next is called for the second time, the function is reentered and start from the very next statement, from where it left off
                                            # you will SURPRISED to read about coroutine, coyield and coreturn -- which were added in C++ 20 [we are seriously outdated, look at the memory layout of these features]
                                for i in range(20):
                                print(next(b))
    
                                c = list(a) # both these lines will cause you machine to hang,
                                d = list(b) # because, generator object will be iterated forever to fill up the list. So caution - advised.
                                # Apart from the above mentioned drawback, generators just remembers, only the required information to move ahead with execution.
                                # for our examples -- first two seed elements will be remembered in a and b respectively.