question about generators

Greg Ewing see_reply_address at something.invalid
Mon Aug 19 20:08:06 EDT 2002


David Eppstein wrote:

> But the set of generators currently involved in yield every statements 
> doesn't form a stack, or even a set of paths

>
> Now that I think about it, though, a generator can only be calling 
> "yield every" on one other generator,

 >

> When any generator x is called, perform the following steps:
>   while ancestor(x) is not x itself but has terminated:
>       ancestor(x) = child(ancestor(x))
>   while ancestor(ancestor(x)) != ancestor(x):
>       ancestor(x) = ancestor(ancestor(x))
>   perform actual generator call on ancestor(x)



I've thought about this a bit more, and I think it can be done
a lot more simply than that. All that's needed is a pointer in
each generator-iterator that points to the subject of the
current yield-every statement being executed, if any.

The next() method of the generator-iterator first checks this
pointer, and if it's not null, does a next() on it instead.
If it's null, or calling next() on it raises StopIteration,
carry on executing until the next yield as usual.

This will still require going down a chain of next() methods
when generators are nested, but the calls will all be C calls
and should therefore be quite fast.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list