pythongenerator

What's the benefit of generators when compared to iterators?


Generators seem like big deal in Python, new features are added to them now and then and so on.

As far as I can see, instead generators you could always use an object with iterator interface. Is (usually) better conciseness the only benefit of generators or am I missing something?


Solution

  • Yes, iterators are a more general construct, and anything you could do with a generator could be done with an iterator.

    However, generators are really nice tool to express certain ideas in a very clean and concise fashion, for which iterators would become cumbersome.

    For example, here's a simple function:

    def count_to(m):
        n = 0
        while n <= m:
            yield n
            n += 1
    

    Nice and easy. Here's the same thing as an iterator:

    class CountTo:
        def __init__(self, m):
            self.m = m
            self.n = 0
        def __iter__(self):
            return self
        def next(self):
            if self.n <= self.m:
                cur, self.n = self.n, self.n + 1
                return cur
            else:
                raise StopIteration()
    

    One is 5 lines, the other is 12. The generator expresses the iteration process very succintly, while the iterator obfuscates it with explictly-maintained state and boilerplate code.

    A lot of Python's philosophy is based around readability and simplicity. In keeping with this, I feel that generators offer a nicer interface for a broad class of tasks that would otherwise require iterators. Yes, iterators are more powerful, but the syntactic advantages of generators certainly can't be overlooked.