Iterators & generators & coroutines

Tim Peters tim_one at
Wed Feb 16 00:55:23 EST 2000

[Aahz Maruch, on ways to "spell" generators]
> ...
> Because now you either have the for construct implicitly create a new
> generator frame or you cannot do
> b = BinTree()
> for node in b.traverser():
> 	for node in b.traverser():
> I would much rather create the generator frames explicitly as in the
> following (I'm now assuming my later idea that a call to a generator
> creates a generator frame that can be used like a function)
> b = BinTree()
> g1 = b.traverser()
> for node in g1():
> 	g2 = b.traverser()
> 	for node in g2():
> It just seems more Pythonic to me.

It's certainly Pythonic to expose the machinery, but also Pythonic to
provide some sugar for the most common cases.  This need not be an either/or

Python currently hides the generation of the "loop index" that supports the
__getitem__ protocol, and that it *didn't* expose the machinery there leads
to clumsiness like the common (& excessively novel):

    for i in range(len(sequence)):

idiom.  The bulk of for loops don't need the loop index, though, and we're
all delighted to use the simpler

    for thing in sequence:

when we can (and that still generates the integers in range(len(sequence)),
but all under the covers).  I expect generators would be very similar in

less-typing-or-more-power-is-a-nice-choice-to-offer-ly y'rs  - tim

More information about the Python-list mailing list