N
Neil Cerutti
For use in a hand-coded parser I wrote the following simple
iterator with look-ahead. I haven't thought too deeply about what
peek ought to return when the iterator is exhausted. Suggestions
are respectfully requested. As it is, you can't be sure what a
peek() => None signifies until the next iteration unless you
don't expect None in your sequence.
Using itertools.tee is the alternative I thought about, but
caveates in the documentation disuaded me.
class LookAheadIter(object):
""" An iterator with the a peek() method, so you can see what's coming next.
If there is no look-ahead, peek() returns None.
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, None)
"""
def __init__(self, data):
self.iter = iter(data)
self.look = self.iter.next()
self.exhausted = False
def __iter__(self):
return self
def peek(self):
if self.exhausted:
return None
else:
return self.look
def next(self):
item = self.look
try:
self.look = self.iter.next()
except StopIteration:
if self.exhausted:
raise
else:
self.exhausted = True
return item
iterator with look-ahead. I haven't thought too deeply about what
peek ought to return when the iterator is exhausted. Suggestions
are respectfully requested. As it is, you can't be sure what a
peek() => None signifies until the next iteration unless you
don't expect None in your sequence.
Using itertools.tee is the alternative I thought about, but
caveates in the documentation disuaded me.
class LookAheadIter(object):
""" An iterator with the a peek() method, so you can see what's coming next.
If there is no look-ahead, peek() returns None.
... print (a, look.peek())>>> nums = [1, 2, 3, 4, 5]
>>> look = LookAheadIter(nums)
>>> for a in look:
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, None)
"""
def __init__(self, data):
self.iter = iter(data)
self.look = self.iter.next()
self.exhausted = False
def __iter__(self):
return self
def peek(self):
if self.exhausted:
return None
else:
return self.look
def next(self):
item = self.look
try:
self.look = self.iter.next()
except StopIteration:
if self.exhausted:
raise
else:
self.exhausted = True
return item