Coroutine generators
A generator is a coroutine that generates a sequence of elements by repeatedly resuming itself from the point that it was suspended.
A generator can be seen as an infinite sequence because it can generate an arbitrary number of elements. The caller function can get as many new elements from the generator as it needs.
When we say infinite, we mean in theory. A generator coroutine will yield elements without a definite last element (it is possible to implement generators with a limited range) but, in practice, we must deal with issues such as overflow in the case of numerical sequences.
Let’s implement a generator from scratch, applying the knowledge we have gained in the previous sections of this chapter.
Fibonacci sequence generator
Imagine we are implementing an application and we need to use the Fibonacci sequence. As you probably already know, the Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones...