Iterators & generators & coroutines

Aahz Maruch aahz at netcom.com
Thu Feb 17 10:38:26 EST 2000


In article <sajm45t62pd47 at corp.supernews.com>,
Evan Simpson <evan at 4-am.com> wrote:
>
>BinTree is a normal class, which produces ordinary instances which
>implement a binary tree.  BinTree has a method 'traverser', which
>returns an object.  This object steps along the binary tree and
>returns a node each time its __getitem__ is called, then raises an
>exception when it runs out of tree.  Instead of maintaining some kind
>of explicit state in the object, it simply uses continuations to
>implement __getitem__ in a clear, natural fashion.  The only data in
>the object is the continuation for __getitem__ and a reference to the
>BinTree instance.
>
>Calling b.traverser() twice, as above, just creates two traversal
>objects which independently walk the tree.

Hmmmm....  On second thought, I guess what you're suggesting would work,
as long as BinTree.traverser() returns a generator object (instead of
returning a list) and the for construct understands how to use generator
objects.

(I was still stuck in my original idea when I disagreed with you, where
I was thinking that BinTree.traverser() was an ordinary method that
required a keyword to create a generator object.  I now think that's a
Bad Idea and that BinTree.traverser() should be unusable as anything
other than the creator of generator objects, which requires a keyword
when defining BinTree.traverser().)

>Aahz Maruch <aahz at netcom.com> wrote in message
>news:88cg9r$10t$1 at nntp9.atl.mindspring.net...
>>
>> 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():
>
>So g1 and g2 are generators, and g1() and g2() are 'generator frames', yes?

Not quite.  g1 and g2 are generator objects (aka "generator frames");
g1() and g2() are calls to the generator that either return a value or
raise an exception.

>So what is a 'generator frame'?  Perhaps that is what I'm not getting.

"Generator frame" is functionally equivalent to "generator object"; I
prefer to use "frame" in analogy with "stack frame" to make clear that
the object has a local namespace and program counter.  If nothing else,
generators will guarantee the demise of Python's "two namespace" rule.
(Sort of.  Each frame will still maintain the two namespace rule.)
--
                      --- Aahz (Copyright 2000 by aahz at netcom.com)

Androgynous poly kinky vanilla queer het    <*>     http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6

Our society has become so fractured that the pendulum is swinging
several different directions at the same time



More information about the Python-list mailing list