Does a StopIteration exception automatically propagate upward through my iterator?
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)开发者_如何学Python:
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.
In this case the StopIteration
exception will be propagated.
What happened when you tried it? :-)
But yes, StopIteration exception are not special and will propagate until something traps them. The next() method does not trap them, and self.inner_iterator.next() will raise a StopIteration when there is nothing left to iterate over.
精彩评论