[Python-ideas] Add lookahead iterator (peeker) to itertools

Terry Reedy tjreedy at udel.edu
Mon Feb 25 13:03:12 CET 2013


On 2/25/2013 5:08 AM, Paul Moore wrote:
> On 25 February 2013 09:51, Wolfgang Maier
> <wolfgang.maier at biologie.uni-freiburg.de> wrote:
>> Terry Reedy <tjreedy at ...> writes:
>>
>>> class lookahead():
>>>       "Wrap iterator with lookahead to both peek and test exhausted"
>> ...
>>
>> +1 That's a nice tool that I'd love to have in itertools.
>
> It's not a bad idea, but I don't like the fact that as written it
> turns a finite iterator into an infinite one (returning an endless
> sequence of sentinels after  the underlying iterator is exhausted).

This is a bug in this re-write. The corrected .__next__

     def __next__(self):
         if self:
             ret = self.peek
             self._set_peek()
             return ret
         else:
             raise StopIteration()

passes the test with this addition

     try:
         next(it)
         assert False, "Next should have raised StopIteration"
     except StopIteration:
         pass

 >>> list(lookahead('abc')) == list('abc')
True

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list