[Tutor] Iterable Understanding
Martin Walsh
mwalsh at mwalsh.org
Mon Nov 23 15:17:42 CET 2009
Stephen Nelson-Smith wrote:
> Martin,
>
>> def __iter__(self):
>> while True:
>> for logline in self.logfile:
>> heappush(self.heap, (timestamp(logline), logline))
>> if len(self.heap) >= self.jitter:
>> break
>> try:
>> yield heappop(self.heap)
>> except IndexError:
>> raise StopIteration
>
> In this __iter__ method, why are we wrapping a for loop in a while True?
>
> S.
Are you more interested in one of the loops over the other? Do you have
a more specific question?
The for loop is a means to populate the heap to a predefined size before
this iterator yields any values. You may have noticed that the first
time through the heap is empty so it will loop a number of times, as
defined by self.jitter, while subsequent entries into the loop will
break after only one execution. Perhaps not the most efficient approach
-- not sure either way, you'll have to test.
The while True loop is where values are yielded, until the heap is empty
again (heappop raises an IndexError) -- a fairly common pattern for
generators in general, I think.
The way I see it (not a programmer by trade or training, FWIW), both
loops have something like a do-until style.
HTH,
Marty
More information about the Tutor
mailing list