[Tutor] How does this work (iterating over a function)?

Danny Yoo dyoo at hashcollision.org
Wed Jul 9 22:03:20 CEST 2014


It might also be useful to see what an equivalent version of that
fib() iterator looks like if we don't take advantage of generators
ourselves.  Here's an attempt at it:

###############################################
def fib1(max):
    a, b, = 0, 1
    while a < max:
        yield a
        a, b, = b, a+b


class fib2(object):
    def __init__(self, max):
        self.max = max
        self.a, self.b = 0, 1

    def __iter__(self):
        return self

    def next(self):
        if self.a >= self.max:
            raise StopIteration
        result = self.a
        self.a, self.b = self.b, self.a + self.b
        return result


## We should see the same output between this:
for n in fib1(10):
    print n,
print
## and this:
for n in fib2(10):
    print n,
###############################################

fib1 is the original iterator of this thread.  fib2 is an iterator
that manages its state by itself.  The difference is that when we're
writing a generator, we can depend on the resuming part to restore our
state when we want to pick up the next value.  In contrast, in the
version without generators, we have to manage all that state
ourselves.

For this example, it's not necessarily hard, but it's slightly tedious.

That's why generators are so closely tied to iterators: generators
make it really easy to write an iterator.  You can write an iterator
without using the generator feature, but it can be a hassle.


More information about the Tutor mailing list