Monday, August 24, 2009

"yield"ing some python

def even():
    for i in range(10):
        if i%2==0
           yield i



Was playing around with python simply because i am bored. I discovered the keyword yield. Which is a Simple Generator in Python. Which is in PEP 255.
For information, generator is a type of routines that can be used to control a loop. Instead of having a function that return the whole list or array. You can yield it one by one, using the yield keyword. As the function above. 

With the function above, you can. 

for i in even():
    print i
 

Or 
i=even()
while i:
    print i.next()

While the second one will ends with the error. I should find out what is the handler for the exception. 
I think it is pretty cool. But really I still trying to figure out what i can use this for. 

1 comment:

  1. Traceback (most recent call last):
    File "/tmp/test.py", line 7, in <module>
    print i.next()
    StopIteration

    so just catch StopIteration.

    while i:
    try:
    print i.next()
    except StopIteration:
    break


    yield is useful if you are generating large list of objects where if you utilize normal list output would cause performance impact. Also useful if you are going to do a list generator with continuous non-stop output. It can also be used to simplify coding of functions that generate lists.

    ReplyDelete