Testing for empty iterators?

Paul Rubin http
Sun Jul 4 15:50:31 EDT 2004


Peter Otten <__peter__ at web.de> writes:
> An alternative would be
> 
> self.assertRaises(StopIteration, getThingIterator().next)

Note that all those methods "consume" at least one element of the
iterator.  You need something like ungetc for iterators (untested code):

    class wrapper:
       def __init__(self, iterator):
          self.iterator = iterator
          self.pushback = []
       def __next__(self):
           if self.pushback:
               return self.pushback.pop(0)
       def is_empty(self):
           if self.pushback:
               return False
           try:
               self.pushback.append(self.iterator.next())
               return False
           except StopIteration:
               return True

Maybe something like that should go into itertools, if it's not
already there.  Or the is_empty operation could be built into iterators.



More information about the Python-list mailing list