[Tutor] __iter__ loops, partitioning list among children

Kent Johnson kent37 at tds.net
Tue Aug 26 13:20:41 CEST 2008


On Tue, Aug 26, 2008 at 1:36 AM, Eric Abrahamsen
<eric at ericabrahamsen.net> wrote:

> So my test case: a Month has a 'child' attribute pointing at Week, which has
> a 'child' attribute pointing at Day, so they all know what kind of child
> instances iteration should produce. With nested loops, a Month produces one
> Week, that Week produces seven Days, then the next Week is produced, it
> makes seven more Days, etc. That much is easy.

If all you want to do with the nested Month, etc is to iterate the
events in them, you could probably use a shared iterator. It would
have to be able to push-back items so that when you hit the
out-of-range item you could push it back on the iterator.

> Then there's self.events. My original code looped over all of self.events
> for each child produced. A Month loops over its events four times, a Week
> seven times. This was the straightforward implementation, but it seemed
> inefficient. (I also, as you point out, might have been wrong about the way
> django QuerySets work). My thought was that only one loop over self.events
> should be necessary, in theory, since they're sorted by date.

Instead of direct use of the list iterator, you could pass the list
and the starting index around. Then you don't have to keep finding
your place.

> A for loop creates an iterator from a sequence and calls next() on it, and
> it creates an entirely new iterator each time you start a new for loop:

I still don't understand your code but you may have another
misconception. Calling iter() on an iterator returns the same
iterator; it does not make a new iterator that holds the same place.
You can use itertools.tee() to split an iterator if that is what you
want to do.

Kent


More information about the Tutor mailing list