I'm implementing an iterator in Python that wraps around another iterator and post-processes that iterator's output before passing it on. Here's a trivial example that takes an iterator that returns strings and prepends FILTERED BY MYITER:
to each one:
class MyIter(object):
"""A filter for an iterator that returns strings."""
def __init__(self, string_iterator):
self.inner_iterator = string_iterator
def __iter__(self):
return self
def next(self):
return "FILTERED BY MYITER: " + self.inner_iterator.next()
When the inner iterator finishes, it will raise a StopIteration exception. Do I need to do anything special to propagate this exception up wo whatever code is using my iterator? Or will this happen automatically, resulting in the correct termination of my iterator.
You do not have to do anything special - the StopIteration
exception will be propageted automatically.
In addition - you may want to read about the yield
keyword - it simplifies creation of generators/iterators a lot.