Return from an iterator and then throw StopIteration

georg picture georg · Feb 22, 2012 · Viewed 8.2k times · Source

What would be the nice way to return something from an iterator one last time when it's exhausted. I'm using a flag, but this is rather ugly:

class Example():

    def __iter__(self):
        self.lst = [1,2,3]
        self.stop = False # <-- ugly            
        return self

    def next(self):
        if self.stop:  # <-- ugly
            raise StopIteration
        if len(self.lst) == 0:
            self.stop = True            
            return "one last time"
        return self.lst.pop()

Background: I'm fetching an unknown amount of strings from an external source and send them further down to the caller. When the process is over, I want to emit a string "x records processed". I have no control over calling code, so this must be done inside my iterator.

Answer

Dan Gerhardsson picture Dan Gerhardsson · Feb 22, 2012

Maybe you can use a generator function instead:

def example():
    lst = [1, 2, 3]
    while lst:
        yield lst.pop()
    yield 'one last time'