Iterators & generators & coroutines

Evan Simpson evan at 4-am.com
Tue Feb 15 17:52:53 EST 2000


Aahz Maruch <aahz at netcom.com> wrote in message
news:88cg9r$10t$1 at nntp9.atl.mindspring.net...
> In article <sajg8pv32pd171 at corp.supernews.com>, Evan Simpson
<evan at 4-am.com> wrote:
> >Why attach such significance to it?  Why not just...
> >
> >b = BinTree()
> >for node in b.traverser():
>
> 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 think I'm missing something, probably something simple.  Let me lay out my
implicit assumptions about how I think this would work; Stop me when I run
off the tracks, please :-)

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.

> 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?
So what is a 'generator frame'?  Perhaps that is what I'm not getting.

Cheers,

Evan @ 4-am





More information about the Python-list mailing list