initial commit
[fmms] / src / mms / iterator.py
1 #
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
5 #
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
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
17 class PreviewIterator(object):
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     """
29     def __init__(self, *args):
30         self._it = iter(*args)
31         self._cachedValues = []
32         self._previewPos = 0
33     def __iter__(self):
34         return self
35     def next(self):
36         self.resetPreview()
37         if len(self._cachedValues) > 0:
38             return self._cachedValues.pop(0)
39         else:
40             return self._it.next()
41     
42     def preview(self):
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     
63     def resetPreview(self):
64         self._previewPos = 0