Pages

Saturday, December 26, 2015

Python Generators

Python provides generator functions as a convenient shortcut to building iterators. A generator is simply a function which returns an object on which you can call next, such that for every call it returns some value, until it raises a StopIteration exception, signaling that all values have been generated. Generators could be thought of as shorthand for creating an iterator. A Basic example of the Iterator or generator can be checked as,

>>> g =(x for x in range(10))
>>> g.next()
0
>>> g.next()
1
>>> g.next()
2
>>> g.next()
3
>>> g.next()
4

Now lets create a Basic generator. A Python generator is created using a Yield Keyword. A yield statement pauses the function saving all its states and later continues from there on successive calls. yield is just like return. It returns whatever you tell it to. The only difference is that the next time you call the function, execution starts from the last call to the yield statement.

So consider if you have a method which returns char by char in a String “hello”. Now when the method is defined as a Generator by using the yield keyword, we will be saving the state of the method. So at one point we called String.next() ,we receive a Char “h” and after some point in the code we used the same above call which will give the next char “e”.

The key advantage to generators is that the "state" of the function is preserved, unlike with regular functions where we will lose the state. A secondary advantage is that some of the function call overhead is avoided, though this is a usually a minor advantage.

A basic usage of the yield will be something like,
>>> def foo(n):
...     yield n
...     yield n+1
...

>>> for n in foo(6):
...     print(n)
...
6
7

Now let’s see how we can write the same Reverse method using generators with the Yield keyword,

#!/software/python/2.7

def Reverse(data):
    for index in range(len(data)-1,-1,-1):
        yield data[index]

def Main():
    ref = Reverse("This is Jagadish")
    for c in ref:
        print c

if __name__  == "__main__":
    Main()


So a generator function is the one which will return a generator object which is the Reverse() method. Now when we run the above code we see,

[djas999@vx181d imp]$ python hello.py
h
s
i

***

No comments :

Post a Comment