Skip to end of metadata
Go to start of metadata

Note: If you are not familiar with the generator concept, this Generator Breakdown page should be read before continuning.

Generator expressions are defined through the pattern:

Generator expressions can be used as return values:

Generator expressions can be stored in variables:

Generator expressions can be used as arguments to functions:

In all cases the evaluation of each inner expression happens only on demand as the generator is consumed by a for in loop.

Generator expressions capture their enclosing environment (like closures do) and thus are able to affect it by updating variables:

As well as being affected by changes to captured variables:


boo's variable capturing behavior differs in behavior from python's in a subtle but I think good way:

This program properly prints the sins followed by the cosines of 0, 1, 2 because for controlled variable references (such as f) in boo generator expressions as well as in closures are bound early.

If you don't know what the python behavior would be check this document.

  • No labels