Code Comments

Code Comments

Tips and short tutorials on various programming technologies

Code Comments RSS Feed
 
 
 
 

Python Yield Example

In Python, there is a bit of functionality that makes it convenient at times to process data while it is being processed inside another method. For example, let’s say you are searching for files within a directory that match a certain pattern, but you don’t want to wait the full time for the files to be found before you started processing them. You can use what’s called a generator which basically sends out the results as they are found within that method.

Or let’s say you were retrieving results from a database or data file and wanted to process them one at a time rather than storing them all in a list (which can be very memory intensive). Generators can come in very handy for this. In Python, a generator is created using the yield keyword.

Here’s the basic structure of how you use it:

def yieldExample():
    for x in getResult():
        yield x

Then to invoke this method, you would do it this way:

for y in yieldExample():
    print y

This post shows an example of how you would use yield and explains more detail.

Leave a Reply