[Python-Dev] alternate reiter proposal

John Williams yahoo-mail.20.johnw@antichef.com
Fri, 30 Aug 2002 10:10:26 -0700 (PDT)


Hi, this is my first post, so go easy on me! :-)

I got this idea from the "cogen" discussion, seeing how the lack of a
reliable re-iterability test makes it hard to write lazy multi-pass
algorithms.  Rather than (1) assuming iterators are re-iterable, (2)
"forcing" iterators to be re-iterable by eagerly converting them to
lists, or (3) trying to heuristically guess whether an iterator is
re-iterable, why not combine the best of (1) and (2) while avoiding (3)
entirely?

This class will lazily convert an interator to a list on the first pass
and then iterate over the saved list on all subsequent passes.

class reiter(object):
    def __init__(self, iterable):
        self.iterator = iter(iterable)
        self.cache = []
    def __iter__(self):
        if self.iterator is None:
            return iter(self.cache)
        else:
            return self
    def next(self):
        try:
            element = self.iterator.next()
            self.cache.append(element)
            return element
        except StopIteration:
            self.iterator = None
            raise


__________________________________________________
Do You Yahoo!?
Yahoo! Finance - Get real-time stock quotes
http://finance.yahoo.com