[Python-Dev] Short-circuiting iterators

Edward Loper edloper at gradient.cis.upenn.edu
Wed Nov 30 20:36:54 CET 2005

> I had an idea this morning for a simple extension to Python's iterator
> protocol that would allow the user to force an iterator to raise
> StopIteration on the next call to next().  My thought was to add a new
> method to iterators called stop().

There's no need to change the iterator protocol for your example use 
case; you could just define a simple iterator-wrapper:

class InterruptableIterator:
     stopped = False
     def __init__(self, iter):
         self.iter = iter()
     def next(self):
         if stopped:
             raise StopIteration('iterator stopped.')
         return self.iter.next()
     def stop(self):
         self.stopped = True

And then just replace:
>     generator = some_generator_function()
     generator = InterruptableIterator(some_generator_function())


More information about the Python-Dev mailing list