Re: [Tutor] PolyRange -- iterator -- PS
by Hugo Arts other posts by this author
Nov 5 2009 3:22AM messages near this date
Re: [Tutor] PolyRange -- iterator -- PS
|
Re: [Tutor] PolyRange -- iterator
On Thu, Nov 5, 2009 at 10:39 AM, spir <denis.spir@[...].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 req
uired, 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 fo
llowing 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
_______________________________________________
Tutor maillist - Tutor@[...].org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
Thread:
Spir
Hugo Arts
Spir
Hugo Arts
Stefan Lesicnik
|