[Tutor] PolyRange -- iterator -- PS

Hugo Arts hugo.yoshi at gmail.com
Thu Nov 5 12:19:28 CET 2009


On Thu, Nov 5, 2009 at 10:39 AM, spir <denis.spir at free.fr> wrote:
>
> 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.
>

This is actually correct. An iterator still requires a next method.
The nice thing about generator functions is that calling them creates
a generator object, which supplies the next method for you
automatically. As below:

>>> a = PolyRange((10, 20), (30, 40))
>>> iter(a)
<generator object at 0x7fe8092c38c0>
>>> b = iter(a)
>>> b.next()
10
>>> b.next()
11

etc. A generator expression does essentially the same thing.


> 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):
>
> <snip example>
>
> PS: Just checked and works as expected with generator.
>

Yes, every time you call iter(), a new generator object is created,
which works independently of other generators.

As an aside, I just thought of an even shorter implementation that
does not sacrifice clarity, using the itertools module:

#this imported at the top of the file
import itertools

def __iter__(self):
    return itertools.chain(*self.ranges)

HTH,
Hugo


More information about the Tutor mailing list