Python generators you had me at first yield

This post is added as a reference for myself.

I’ve been reading a lot about writing clean, readable and performant Python code. One feature that I now adore are generators. In the words of Python guru David Beazley a generator is:

“a function that produces a sequence of results instead of a single value”

The presentation above is an incredible overview of this amazing feature and I’ve been taking advantage of it whenever I can. Here is one case where I was able to use this today:

#!/usr/bin/env python

import os
import re

SYSFS_TAPE_PATH = "/sys/class/scsi_tape/"

def find_drives():
    """
       Return a list of tape drives
    """
    for drive in os.listdir(SYSFS_TAPE_PATH):
        if re.match(r'^nst[0-9]+$', drive):
            yield drive

for drive in find_drives():
    print drive

Running the script produces all of the drives on the system:

$ ./generator 
nst0
nst1
nst2
nst3

In the past I would have created a list and returned it after processing all of the drives in the scsi_tape directory. With generators that is no longer necessary and I find the code is much more readable. A huge thanks to David for the great presentation! Hopefully one day I will get to take one of his awesome Python programming classes.

1 thought on “Python generators you had me at first yield”

Leave a Reply

Your email address will not be published. Required fields are marked *