Calling a generator multiple times

Greg Ewing greg at cosc.canterbury.ac.nz
Mon Dec 10 00:45:34 EST 2001


Just van Rossum wrote:
> 
> I mentioned the
> archives of python-iterators list before, but I think the PEP is a better
> reference:
>        http://python.sourceforge.net/peps/pep-0255.html

I don't think reading the list discussions is going to
change anyone's mind. I read them all the first time
around, and they didn't change mine.

The crux of the matter seems to be in this paragraph
from the PEP:

    In practice (how you think about them), generators *are*
    functions, but with the twist that they're resumable.  The mechanics
of
    how they're set up is a comparatively minor technical issue, and
    introducing a new keyword would unhelpfully overemphasize the
    mechanics of how generators get started (a vital but tiny part of a
    generator's life).

This could perhaps do with some elaboration. What I
think it's saying is that, the vast majority of the
time, generators will be called in the context of a
for loop:

   for x in some_generator(some_args):
      ...

Now, in that case, if you squint at it and don't 
question anything too closely, you can pretend it's
Icon and that the generator proceeds normally until
it hits a yield at which point it starts behaving
something like a couroutine. As long as you're
willing to accept that fiction, you don't need to
know about the magic going on when the generator is
first called -- it's an implementation detail.

But if you stop and think "Hey, wait a minute,
how does that actually *work*?" and start playing
around with the generator on its own, the magic
starts showing through, and generators stop
looking like ordinary functions at all.

It's at *that* point that some of us get the very
strong feeling that there is something wrong with
declaring a generator just like a function. Telling
us to go read the discussions or the PEP does
nothing to dispel that feeling. We've been there,
and have come to a different conclusion.

-- 
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