question about generators

greg greg at
Fri Aug 16 11:16:15 CEST 2002

David Eppstein wrote:
> Suppose you have a long call chain of "yield every" statements 
>  -- say the length of the chain is L.  Then the obvious
> implementation is to simply expand each "yield every x" statement into
> "for i in x: yield i".  But, this would incur O(L) overhead for each
> generated item.

I have an idea about this, which I hope I'll get around to
following up. I *think* it will be possible to optimise
"yield every x" in the case where x is a generator-iterator,
to eliminate the call chain.

This would be done by keeping a stack of active generator-
iterators somewhere (not exactly sure where yet). When you
hit a "yield every", you push the sub-generator-iterator
onto the stack, so that subsequent yields go directly to
the most recent one. When it is exhausted, you pop the
stack and try to resume the next most recent one. When
the stack is empty, you raise StopIteration.

Greg Ewing

More information about the Python-list mailing list