An iterator with look-ahead

Neil Cerutti horpner at yahoo.com
Wed Jan 10 09:31:47 EST 2007


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.

        >>> nums = [1, 2, 3, 4, 5]
        >>> look = LookAheadIter(nums)
        >>> for a in look:
        ...    print (a, look.peek())
        (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

-- 
Neil Cerutti
We've got to pause and ask ourselves: How much clean air do we really need?
--Lee Iacocca



More information about the Python-list mailing list