[Tutor] PolyRange -- iterator -- PS

spir denis.spir at free.fr
Thu Nov 5 10:39:09 CET 2009

Le Wed, 4 Nov 2009 18:17:21 +0100,
Hugo Arts <hugo.yoshi at gmail.com> s'exprima ainsi:

> Now, the code. If you write __iter__ as a generator, you won't have to
> write a next method at all. It simplifies The thing a whole lot:
> def __iter__(self):
>     for range in self.ranges:
>         for item in range:
>             yield item
> That's it. Alternatively, you could turn the whole thing into a
> one-liner and just return a generator expression from __iter__:
> def __iter__(self):
>     return (item for r in self.ranges for item in r)
> It's not as clear though, and it doesn't save that much space. I like
> the first one slightly better.

Thank you very much! That's exactly what I expected. Was sure my code was uselessly heavy. Actually, when reading the doc about iteration, I had wrongly understood that next() is required, too.

Now, I agree with you on your last comment... except that (.. for .. in ..) is precisely the syntax for generator expression (which is much more familiar to me than the use of generator funcs). Still, I will use the first idiom for clarity.

Two additional questions (relative to things manually implemented in my original code):
* What about memorization of "emptyness", meaning the last item is already reached, and following calls will all fail. This is automatic for generators, but...
* Then how do you restart it? With a decoupling of __iter__() and next(), it's possible to have both failure when empty for the same iterator (= call to next()), and 
a new iterator returned by __iter__(), typically for a new "for" statement. Below after a bug correction (attributes needing initialisation):
def testPolyRange():
    for i in pr1: print i,
        print pr1.next()
    except StopIteration,e:
        print "StopIteration"
    for i in pr1: print i,
1 2 5 6 3 4 5 6 7 8 StopIteration
1 2 5 6 3 4 5 6 7 8

PS: Just checked and works as expected with generator.

Thank you again, Denis.
la vita e estrany

More information about the Tutor mailing list