Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

Still having problems understanding generators, huh?

Don't worry - its easy stuff.

The basic syntax is:

Code Block
<expression> for <declarations> in <iterator> <conditional expression>

In practice, it generally looks like this:

Code Block
<local variable> = <expression> for <declarations> in <iterator> <conditional expression>

Let's start off easy:

After the generator expression is run, <local variable> will become an enumerable object that you can iterate through, like an array, list, or collection. The contents of this enumerable object will be a collection of <expression>s.

<expression>s are variables that are put into <local variable> if <conditional expression> returns true. This means means that by using a <conditional expression> in a generator, you can decide which objects should be added to the enumerable <local variable>. <expressions> can be manipulated further: for instance, this syntax is valid:

Code Block
<local variable> = MethodToMutilateExpression(<expression>) for <declarations> in <iterator> <conditional expression>

In this instance, the return value of MethodToMutilateExpression will be added to the enumerable <local variable>. This makes generators useful to filter the input that MethodToMutilateExpression() will be called with.

"for <declarations> in <iterator>" is your typical for loop: "for item in collection," in otherwords.

Here's a simple working example of how generators work.

Code Block
#An array of integers
crazyArray = (0, 1, 2, 3, 4, 5)
#Shazbot. We only want integers that are greater than 3!

#We want an enumerable object composed only of integers > 3.
validIntegers = value for value in crazyArray if value > 3

#Here's some special Boo magic: turn 'ValidIntegers' back into an array!
#We can do this because all objects within validIntegers are really integers.
magic = array(int, validIntegers)
print magic #print the type of this object
print join(magic) #turn this array into a readable string.

Here's the output:

Code Block
4 5