[Python-ideas] Generators are iterators

Chris Angelico rosuav at gmail.com
Sat Dec 13 22:27:56 CET 2014


On Sun, Dec 14, 2014 at 7:19 AM, Ron Adam <ron3200 at gmail.com> wrote:
> I think if function definitons with yield in them created
> generator_instance_factory objects instead of function objects, things would
> be easier to explain.  What it comes down to, is they aren't normal
> functions and it's a bit confusing to think of them that way.

They're no more different than, say, a decorated function that returns
a different function. But if you want a different way to explain them,
here's a similar way to craft an iterator:

class seq_iter:
    def __init__(self, func, *args, **kw):
        self.func = func
        self.args = args
        self.kw = kw
        self.state = 0
    def __iter__(self): return self
    def __next__(self):
        if self.state == -1: raise StopIteration
        ret = self.func(self.state, self, *self.args, **self.kw)
        self.state += 1
        if ret is not self: return ret
        self.state = -1
        raise StopIteration

def sequential_iterator(func):
    @functools.wraps(func)
    def inner(*args, **kw):
        return seq_iter(func, *args, **kw)
    return inner

##### Example usage #####
@sequential_iterator
def ten_squares(idx, finished):
    if idx == 10: return finished
    return idx*idx

The function returned by the decorator isn't the one decorated, but
it's clearly still a function. No reason for it to be a unique type.
This is similar to the relationship between generator functions and
the iterators returned when you call them. It's an alternative way to
write an iterator class, dealing with lots of the bookkeeping for you.

ChrisA


More information about the Python-ideas mailing list