An iterator with look-ahead

Neil Cerutti horpner at yahoo.com
Wed Jan 10 13:06:39 EST 2007


On 2007-01-10, Steven Bethard <steven.bethard at gmail.com> wrote:
> Neil Cerutti wrote:
>> For use in a hand-coded parser I wrote the following simple
>> iterator with look-ahead.
>
> There's a recipe for this:
>
>    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373
>
> Note that the recipe efficiently supports an arbitrary
> look-ahead, not just a single item.
>
>> I haven't thought too deeply about what peek ought to return
>> when the iterator is exhausted. Suggestions are respectfully
>> requested.
>
> In the recipe, StopIteration is still raised on a peek()
> operation that tries to look past the end of the iterator.

That was all I could think of as an alternative, but that makes
it fairly inconvenient to use. I guess another idea might be to
allow user to provide a "no peek" return value in the
constructor, if they so wish.

-- 
Neil Cerutti



More information about the Python-list mailing list