PEP 255: Simple Generators

Tim Peters tim.one at home.com
Mon Jun 18 19:31:44 EDT 2001


[Russell E. Owen]
> This sounds like an interesting and really useful proposal. However,a
> few details are worrisome to me:

You should catch up with the discussion on the Python-Iterators list (as
mentioned in the PEP announcement), where these have already been discussed
several times.  I'll only give brief summaries here.

> * A generator looks like a function until you find the "yield" statement
> inside. I think this will make the code much harder to read. One keyword
> buried anywhere in a function totally changes its behavior. If a
> generator acted like a function until it hit "yield", this wouldn't be
> so bad, but it sounds as if generators have enough significant
> differences (such as restrictions on and a changed meaning for return)
> that they are very different beasts.
>
> I'd much rather see a declaration up front that this is going to be a
> generator. E.g. add a new keyword such as "generator".

Who would this help?  Seriously.  There's nothing special about a generator
to a caller, except that it returns an object that implements the iterator
interface.  While the latter is important to know, there are many ways to
construct iterators in 2.2 without using generators at all.  This is better
communicated via documentation (e.g., make the first line of the docstring
"Generate ..." instead of "Return ...").

On the other end, someone modifying the generator isn't going to miss that
it *is* a generator:  all the control flow will focus on feeding
intermediate results to yield statements.  IOW, you worry too much <wink>.

> * The unusual use of "return" and the associated restriction of no
> expression list. What "return" means in a generator is "raise StopIter",
> not return. I personally really dislike using a keyword for multiple
> vaguely similar purposes. Look at "static" in C++ for an example of
> where this can lead.

"return" means "I'm done" in any kind of function, generator or not.  You
can raise StopIteration instead if you feel you must, but then you're
focusing on an implementation detail, and that's not helping anyone.  Guido
appears to feel quite strongly about this one, so if you want to push it I
suggest finding a better analogy than C++'s (over)use of static.

I'll note that in Icon, "yield" is spelled "suspend", and "return
expression" is allowed, meaning "I'm done, but I have one last useful value
to suspend with".  It's possible Python may grow that meaning too, but it
was thought better to keep it more restrictive at first.





More information about the Python-list mailing list