PEP 255: Simple Generators
Russell E. Owen
owen at astrono.junkwashington.emu
Mon Jun 18 14:32:31 EDT 2001
In article <mailman.992537422.15240.python-list at python.org>,
"Tim Peters" <tim at digicool.com> wrote:
>You can view an HTML version of PEP 255 here:
>
> http://python.sourceforge.net/peps/pep-0255.html
...
>
> This PEP introduces the concept of generators to Python, as well
> as a new statement used in conjunction with them, the "yield"
> statement.
This sounds like an interesting and really useful proposal. However,a
few details are worrisome to me:
* 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".
* 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.
Several proposals come to mind. They are all compatible with each other:
1) Have users explicitly say "raise StopIter" when they mean it. This is
my first choice. Sure it's two words, but has the huge advantages of:
-- saying exactly what it means
-- not cluttering up "return" with multiple meanings
-- not having to explain to users why no expression list is allowed on
"return"
-- it leaves the door open for a Better Way, should one be proposed;
meanwhile, no damage has been done
2) Add a keyword, such as "stop". It could always raise StopIter, or
raise a new exception Stop in a non-generator and StopIter in a
generator. On the plus side, stop might be handy in other contexts. On
the minus side, I doubt it's worth the fuss.
3) Have "return" mean exactly what it means now, but also have a
generator raise StopIter for the next call following a return. This is a
natural meaning for return (and allows an expression list), but has the
disadvantage that it doesn't permit one to say "I'm done and have no
more data to return".
-- Russell
More information about the Python-list
mailing list