Generators: Python has them, and C# is proposing to add them. What are they ?
def GeneratorFunc( n):
for i in range( n):
yield i
for i in GeneratorFunc( 3):
print "i=%d" % i
The call to GeneratorFunc does not execute any of the code inside the GeneratorFunc. Instead it returns an iterator object that we can use in the for loop at the bottom. The for loop implicitly calls the iterator's next() method, which in turn executes the code inside GeneratorFunc. Every time this happens, the yield keyword supplies the value to be returned by the iterator's next() method. The important thing to remember is that all the local variables, and stack state, inside the GeneratorFunc body are preserved between invocations of the iterator's next() method. All this may be a little clearer if we invoke the iterator directly rather than relying on for to do it...
def GeneratorFunc( n):
for i in range( n):
yield i
iter = GeneratorFunc( 3)
while 1:
print "i=%d" % iter.next()
All well and good, you may say. But where can I apply this idiom ? I can see tremendous leverage in two common coding areas: recursive tree walks and blocking IO handler code. More later...
