concept generator in category .net

appears as: generators, generator
IronPython in Action

This is an excerpt from Manning's book IronPython in Action.

Sequences are examples of a type of object that you can iterate over. You can also create other types of objects that can be iterated over: iterators and generators.

A key fact about sequences is that you can index them, or ask them for their nth member. Because iterators and generators produce their members dynamically, you can’t index into them.

When a function (or method) uses yield, it becomes a generator. Generators are a lightweight form of coroutines.

Where a function uses yield, the value is returned and execution of the generator is suspended. On the next iteration, execution continues at the point it was suspended. Complex iteration can be implemented with generators, without having to explicitly store state.

Listing 8.5 is an example with a Directory object that stores all the files in a specified path from the filesystem. It recurses into subdirectories, storing them as Directory objects. The __iter__ method is implemented as a generator and also recurses through subdirectories.

Listing 8.5. Directory class that supports iteration with a generator

Because the __iter__ method yields, it returns a generator, which is a specific kind of iterator. As an iterator, it has the next method available.