MCPcopy Create free account
hub / github.com/idank/explainshell / Peekable

Class Peekable

explainshell/util.py:29–84  ·  view source on GitHub ↗

>>> it = Peekable(iter('abc')) >>> it.index, it.peek(), it.index, it.peek(), next(it), it.index, it.peek(), next(it), next(it), it.index (0, 'a', 0, 'a', 'a', 1, 'b', 'b', 'c', 3) >>> it.peek() Traceback (most recent call last): File " ", line 1, in ? StopIterati

Source from the content-addressed store, hash-verified

27
28
29class Peekable:
30 """
31 >>> it = Peekable(iter('abc'))
32 >>> it.index, it.peek(), it.index, it.peek(), next(it), it.index, it.peek(), next(it), next(it), it.index
33 (0, 'a', 0, 'a', 'a', 1, 'b', 'b', 'c', 3)
34 >>> it.peek()
35 Traceback (most recent call last):
36 File "<stdin>", line 1, in ?
37 StopIteration
38 >>> it.peek()
39 Traceback (most recent call last):
40 File "<stdin>", line 1, in ?
41 StopIteration
42 >>> next(it)
43 Traceback (most recent call last):
44 File "<stdin>", line 1, in ?
45 StopIteration
46 """
47
48 def __init__(self, it):
49 self.it = it
50 self._peeked = False
51 self._peek_value = None
52 self._idx = 0
53
54 def __iter__(self):
55 return self
56
57 def __next__(self):
58 if self._peeked:
59 self._peeked = False
60 self._idx += 1
61 return self._peek_value
62 n = next(self.it)
63 self._idx += 1
64 return n
65
66 def has_next(self):
67 try:
68 self.peek()
69 return True
70 except StopIteration:
71 return False
72
73 def peek(self):
74 if self._peeked:
75 return self._peek_value
76 else:
77 self._peek_value = next(self.it)
78 self._peeked = True
79 return self._peek_value
80
81 @property
82 def index(self):
83 """return the index of the next item returned by next()"""
84 return self._idx
85
86

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected