DZone
generators
and yield
: these two keywords give us great power when we are supposed to produce data that is huge or infinite. The generators
function provides us a way to declare a function that generates an iterator. The generators
function doesn’t have a return
statement, but the yield
statement does (more than one yield
is possible). If the return
statement gets placed inside the generator code, the execution will stop with an exception.
The beauty of generators
is that all local variables and the execution start point are automatically saved between calls; this is because the generators
function doesn’t start execution at the beginning from the function for each call. Only the first call starts at the beginning of the function; the next call onwards, it resumes from the yield
statement. In short, you can see generators as iterators where you can think of the next()
method right there at yield
.
Source: DZone