Generators in Python….


Generators are one of the exotic features present in python which makes it a very,very high level programming language.Generator, simply put, is a python function with keyword yield in it. The yield keyword will suspend the function’s execution,remember the state of all the local variables and will yield a value,unlike a normal function which will execute till completion and cannot be resumed.A generator,on other hand, can be resumed from the point where it has been suspended by an external call.Here is an simple example which will illustrate the concept better(Kindly excuse the bad variable names)…..

>>>def numgen( ):
>>>      i = 0     
>>>      while True:
>>>          yield i                 
>>>          i = i + 1

That is a simple generator which generates numbers from 0 to an undefined upperlimit one by one, when asked for by the external code.Here is how we use the above generator….

>>>numbergenerator = numgen()

It is pretty simple to close the generator once you are done with it…


That closes the generator.An attempt to make another next call throws an StopIteration exception(This must be caught and silenced using a try and except statement in a production code.).

The above example illustrates the fact that Generators can be used to implement infinite sequences.The lack of an defined upper bound indicates that generators do not pre-calculate all the required values,but calculates them only when they are asked for it.This saves a huge amount of space. Generators can be used in a much more constructive manner than described here. For example,They can be used to read a text file and yield one word per time,while the function on the other end can use the generator’s output to construct a dictionary which can store the number of times each word has occured in the text file.Generators, in a way, provide a way to abstract data generation and data processing.The data generation part can be handled by the generator, while the data processing can be done by another function which can create a local generator object to generate the required data.

For more information on Generators, check out the following links….

Also check out the python’s help documentation for more information on generators.

Pliss point out any mistakes(if any) which i might have inadvertently made in the post.

One Response to “Generators in Python….”

  1. Heyo chaps, any further Python tutes.?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: