1
2
3
4
5
6
7
8
9 """
10 PyMMS library: Iterator with "value preview" capability.
11
12 @version: 0.1
13 @author: Francois Aucamp C{<faucamp@csir.co.za>}
14 @license: GNU Lesser General Public License, version 2
15 """
16
18 """ An C{iter} wrapper class providing a "previewable" iterator.
19
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.
25
26 From the user point of view, this class supersedes the builtin iter()
27 function: like iter(), it is called as PreviewIter(iterable).
28 """
30 self._it = iter(*args)
31 self._cachedValues = []
32 self._previewPos = 0
36 self.resetPreview()
37 if len(self._cachedValues) > 0:
38 return self._cachedValues.pop(0)
39 else:
40 return self._it.next()
41
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()}.
45
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.
48
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()}.
54 """
55 if self._previewPos < len(self._cachedValues):
56 value = self._cachedValues[self._previewPos]
57 else:
58 value = self._it.next()
59 self._cachedValues.append(value)
60 self._previewPos += 1
61 return value
62
65