Monday, June 27, 2011

Python Generators

When we write a program it mat contain a series of named blocks. Each of those performs a single logical action. Named blocks are usually performed one after another as a sequence of statements from within another block.

In this example, the pow2 function is performed completely before the for loop is run.

The list called "powers" is constructed completely and stored in memory while the for loop is run. That's not a problem in this case with a list of ten values, but it could be a problem if the list was to contain a billion values.

def pow2(upto):
powers = []
sat = 1
spwr = 1
while spwr <= upto:
powers.append(sat)
sat *= 2
spwr += 1
return powers

def main():
for w in pow2(10):
print w
main()


Python provides an alternative way.i.e. Generator Functions. A generator function is one that does NOT run to completion when it's first called - instead, it only runs until it has a value available to return.

A generator function is any function which uses the yield statement.

When the for loop asks for the next element the generator starts or continues function execution at the place it left off. It runs until it reaches a yield statement. The function call is suspended at the yield statement. The generator stores the function call state and returns the given element.

Here's the program provided above, modified to use a generator.

def pow2(upto):
sat=1
spwr=1
while spwr<=upto:
yield sat
sat*=2
spwr+=1

def main():
for w in pow2(10):
print w
main()

Operation is exactly the same as the example above ... but there is NOT an intermediate list produced.Generators provide a very neat way of providing data as required on applications that potentially use huge intermediate lists.


No comments:

Post a Comment