[Python-Dev] Simple generator implementation

Neil Schemenauer nas@arctrix.com
Fri, 16 Mar 2001 05:54:48 -0800


On Fri, Mar 16, 2001 at 03:37:33AM -0800, Neil Schemenauer wrote:
> ... it looks like it would be similer to put this code in the
> switch statement.

Um, no.  Bad idea.  Even if I could restructure the loop, try/finally
blocks mess everything up anyhow.

After searching through many megabytes of python-dev archives (grepmail
is my friend), I finally found the posts Tim was referring me to
(Subject: Generator details, Date: July 1999).  Guido and Tim already
had the answer for me.  Now:

    import sys

    def g():
        for n in range(10):
            suspend n, sys._getframe()
        return None, None

    n, frame = g()
    while frame:
        print n
        n, frame = frame.resume()

merrily prints 0 to 9 on stdout.  Whee!

  Neil