How to write this iterator?

Paul Rubin http
Mon Sep 19 12:54:57 CEST 2005


Hmm, here's an approach using the .throw() operation from PEP 342.
It's obviously untested, since that feature is not currently part of
Python, probably incorrect, and maybe just insane.  I renamed "append"
to "insert_iterator" since "append" usually means put something at the
end, not in the middle.

   from itertools import cycle
   class InsertIterator(Exception): pass

    def itergen(self, *iters):
        while iters:
            try:
               for i,it in (enumerate(it) for it in cycle(iters)):
                  yield it.next()
            except StopIteration:
                del iters[i]
            except InsertIterator, new_iterator:
                # maybe the i here should be i+1?
                iters = [new_iterator] + iters[i:] + iters[:i]

Now you can say

    ig = itergen(it1,it2,...)
    for x in ig:
       ....

and if you want to insert a new iterator, just say

   ig.throw(InsertIterator, new_iterator)



More information about the Python-list mailing list