2 # This library is free software, distributed under the terms of
3 # the GNU Lesser General Public License Version 2.
4 # See the COPYING.LESSER file included in this archive
6 # The docstrings in this module contain epytext markup; API documentation
7 # may be created by processing this file with epydoc: http://epydoc.sf.net
10 PyMMS library: Iterator with "value preview" capability.
13 @author: Francois Aucamp C{<faucamp@csir.co.za>}
14 @license: GNU Lesser General Public License, version 2
17 class PreviewIterator(object):
18 """ An C{iter} wrapper class providing a "previewable" iterator.
20 This "preview" functionality allows the iterator to return successive
21 values from its C{iterable} object, without actually mvoving forward
22 itself. This is very usefuly if the next item(s) in an iterator must
23 be used for something, after which the iterator should "undo" those
24 read operations, so that they can be read again by another function.
26 From the user point of view, this class supersedes the builtin iter()
27 function: like iter(), it is called as PreviewIter(iterable).
29 def __init__(self, *args):
30 self._it = iter(*args)
31 self._cachedValues = []
37 if len(self._cachedValues) > 0:
38 return self._cachedValues.pop(0)
40 return self._it.next()
43 """ Return the next item in the C{iteratable} object, but do not modify
44 the actual iterator (i.e. do not intefere with C{iter.next()}.
46 Successive calls to C{preview()} will return successive values from
47 the C{iterable} object, exactly in the same way C{iter.next()} does.
49 However, C{preview()} will always return the next item from
50 C{iterable} after the item returned by the previous C{preview()} or
51 C{next()} call, whichever was called the most recently.
52 To force the "preview() iterator" to synchronize with the "next()
53 iterator" (without calling C{next()}), use C{resetPreview()}.
55 if self._previewPos < len(self._cachedValues):
56 value = self._cachedValues[self._previewPos]
58 value = self._it.next()
59 self._cachedValues.append(value)
63 def resetPreview(self):