The Yield statement

Larry Bates larry.bates at websafe.com`
Mon Jun 30 19:21:10 EDT 2008


Alex Bryan wrote:
> Okay, so i don't really understand the Yield thing and i know it is 
> useful. I've read a few things about it but it is all programming jargon 
> and so basically it is hard for me to understand. So can anyone give me 
> a description or link me to a site that has a good definition and/or 
> examples of it? If you could I would really appreciate it.

Use yield when you want the function to act as a generator.  That is each time 
it is called it generates a response and returns it, but leaves its state intact 
so that the next time you call it, it can pick up where it left off and continue on.

Best example I ever saw is the code that implements os.walk() function:

def walk(top, topdown=True, onerror=None):
     """
     Example:

     from os.path import join, getsize
     for root, dirs, files in walk('python/Lib/email'):
         print root, "consumes",
         print sum([getsize(join(root, name)) for name in files]),
         print "bytes in", len(files), "non-directory files"
         if 'CVS' in dirs:
             dirs.remove('CVS')  # don't visit CVS directories
     """

     from os.path import join, isdir, islink

     try:
         names = listdir(top)
     except error, err:
         if onerror is not None:
             onerror(err)
         return

     dirs, nondirs = [], []
     for name in names:
         if isdir(join(top, name)):
             dirs.append(name)
         else:
             nondirs.append(name)

     if topdown:
         yield top, dirs, nondirs
     for name in dirs:
         path = join(top, name)
         if not islink(path):
             for x in walk(path, topdown, onerror):
                 yield x
     if not topdown:
         yield top, dirs, nondirs


Actually this code uses yield and is recursive.  Pretty neat.

-Larry



More information about the Python-list mailing list