PEP 255: Simple Generators

Greg Ewing greg at cosc.canterbury.ac.nz
Thu Jun 21 00:52:27 EDT 2001


"Barry A. Warsaw" wrote:
> 
> They are very different because the body of a generator function
> defines the generator object's .next() method, but the def names the
> generator object's factory function.

That's an interesting point -- there are actually two
separate things going on, but the syntax is collapsing
them into one construct.

At one point, I considered proposing that instead of
generator *functions*, there should be a generator
*statement*. A function returning a generator-iterator
would then be written as

  def f(args):
    generator g:
      ...
      yield x
      ...
    return g

The idea was that executing the generator statement
would create a new generator-iterator and bind it
to g. The advantage would be that creation of the
generator-iterator would be made explicit, and the
new keyword would signal that some sort of new flow
control is going on.

Then I got to thinking about whether executing the
generator statement should create a new local
namespace, or whether it should re-use the surrounding
one. The latter could have bad consequences if you
wrote code which executed a given generator statement
more than once in a given function invocation, so it
seems like it should create a new local namespace
for its body to execute in.

But then the generator statement is starting to
take on some of the characteristics of a function
definition, whereas the point of making it a different
statement was to keep them separated.

So in the end I decided that combining their functions
into one statement was a reasonable thing to do after
all. But I still felt that something was needed to
distinguish it from an ordinary function definition,
since it's doing rather *more* than just defining
a function. So I settled on

  generator g(args):
    ...

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list