| Start |
|---|
| The Yield Keyword A Here is an example of the range function, written as a generator: You can see that this function returns a Generator (opens new window) object by inspecting the output of Yielding ValuesThe Generator (opens new window) object can then be iterated over like an array. The above example will output: Yielding Values with KeysIn addition to yielding values, you can also yield key/value pairs. The above example will output: |
| Reading a large file with a generator One common use case for generators is reading a file from disk and iterating over its contents. Below is a class that allows you to iterate over a CSV file. The memory usage for this script is very predictable, and will not fluctuate depending on the size of the CSV file. |
| Why use a generator? Generators are useful when you need to generate a large collection to later iterate over. They're a simpler alternative to creating a class that implements an Iterator (opens new window), which is often overkill. For example, consider the below function. All this function does is generates an array that's filled with random numbers. To use it, we might do This is due to the entire one million random numbers being generated and returned at once, rather than one at a time. Generators are an easy way to solve this issue. |
| Using the send()-function to pass values to a generator Generators are fast coded and in many cases a slim alternative to heavy iterator-implementations.
With the fast implementation comes a little lack of control when a generator should stop generating or if it should generate something else. However this can be achieved with the usage of the Resulting in this Output: |
| Re-writing randomNumbers() using a generator Our Using a generator, we don't have to build an entire list of random numbers to return from the function, leading to much less memory being used. |
Read Article
https://develop.horje.com/learn/1434/reference