[Python-Dev] alternate reiter proposal

Andrew Koenig ark@research.att.com
30 Aug 2002 13:29:50 -0400

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

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

Maybe I'm missing something here, but doesn't this fail if you
try to restart it before it has entirely consumed the input?

Andrew Koenig, ark@research.att.com, http://www.research.att.com/info/ark