[Tutor] iter class

Keith Winston keithwins at gmail.com
Thu Jan 23 20:18:33 CET 2014


On Thu, Jan 23, 2014 at 1:36 PM, Devin Jeanpierre
<jeanpierreda at gmail.com> wrote:

> Again, nothing was incorrect about the example. Every iterator has
> this "problem".

Hmmm. Well, here's what he actually said about that example, since I
don't think I've explained correctly:

*****
With iterators, one thing to watch out for is the return of self from
the __iter__ function. You can all too easily write an iterator that
isn't as re-usable as you think it is. For example, suppose you had
the following class:

{my example here}

This works just like you'd expect as long as you create a new object each time:

>>> for i in MyTrickyIter(['a', 'b']):
...   for j in MyTrickyIter(['a', 'b']):
...      print i, j
a a
a b
b a
b b

but it will break if you create the object just once:

{my example here, yielding only a single a b from the above loop}
******

The difference essentially comes down to the line

...      self.thelist = thelist  # in the "broken" example, vs.

...      self.thelist = iter(thelist)  # the "better" way to do it,
restarts the iterator each time a new loop uses it

I'm pretty sure I'm not really saying this right, it takes time
(apparently, for me) to understand how to speak clearly of these
things. The more important element, of course, is when my fuzzy
speaking speaks to fuzzy thinking, of which I am grateful for
correction.

-- 
Keith


More information about the Tutor mailing list