PEP 255: Simple Generators
Tim Peters
tim at digicool.com
Thu Jun 21 14:57:18 EDT 2001
[Terry Reedy]
> When I first read the PEP, I assumed that def'ed generators would
> somehowreturn the successive yielded values on successive calls (wrong).
Alas, I believe that. For good or ill, PEPs aren't tutorials, they're aimed
much more at developers of Python (as distinguished from developers using
Python). A good user's intro to Python generators doesn't exist yet
(AFAIK).
> ...
> As I now understand it, putting 'yield' somewhere within a function
> body will *also* magically transform the function definition into
> syntactic sugar for an iteration factory function.
Using the grownup words can help <win>: a generator-function returns a
generator-iterator, which latter is an object that implements the iterator
interface. All the *interesting* questions you're wondering about can be
answered by reading the PEP on *iterators* in 2.2. PEP 255 assumes intimate
knowledge of the latter, and indeed doesn't make sense without it.
> ...
> Question: am I correct in thinking that separating
> iterator-generation from iterator-first-use makes it possible to have
> multiple iterators from the same generator in simultaneous use, as in
>
> sq10 = squares(10)
> sq20 = squares(20)
> ...
> ?
Yes, and this follows from that generator-functions return objects that
implement the iterator interface; it's got little to do with generators
themselves (apart from that they're not implemented insanely <wink>). Note
that this is an "advanced" use, though, and I expect that most uses of
generators will be of the simple
for object in generator():
... object ...
form. The underlying iteration machinery is exposed so that advanced users
*can* do fancier things, but you're not required to do fancier things. In a
decade of Python, I believe I can count the number of times I've actually
implemented a __getitem__ method that raises IndexError on one hand; I don't
expect to *habitually* use advanced generator capabilities either -- but
more often that I've used explicit IndexError, because the latter was a much
clumsier approach to iteration.
More information about the Python-list
mailing list