PEP 255: Simple Generators
Tim Peters
tim.one at home.com
Fri Jun 15 17:02:33 EDT 2001
[David S. Harrison, on c.l.py]
> This is an awesome PEP. I have used Icon extensively in the past
> and I have found generators to be very useful and elegant. It was
> not exactly clear in the proposal, but will it be possible to
> enumerate elements outside of the "for" idiom?
The ability is implicit in the PEP's:
Instead a generator-iterator object is returned; this conforms
to the iterator protocol[6],
...
[6] The concept of iterators is described in PEP 234
http://python.sf.net/peps/pep-0234.html
I'm afraid PEPs aren't tutorials, though, and it's a Positive Good not to
repeat info across them.
For a very simple example,
def genid_func(i):
while 1:
yield i
i += 1
getid = genid(5).next
print getid() # prints 5
print getid() # prints 6
print getid() + getid() # prints 7 + 8 = 15
> Sometimes it is useful to get elements out of a generator in different
> parts of a program. For example, the first few elements might be
> consumed by one function, and the next by another. Is this possible
> under PEP 255?
Yes. Curiously, though, it's *not* possible in Icon: generators are tied
to control context there. In Icon you have to use full-blown co-expressions
if you want to get the ability independent of generative control structures.
PEP 255's generators are more capable than Icon's in this respect (but
possibly less capable than Icon's co-expressions).
More information about the Python-list
mailing list