[Tutor] Iterable Understanding
Stephen Nelson-Smith
sanelson at gmail.com
Sat Nov 14 15:40:32 CET 2009
Gah! Failed to reply to all again!
On Sat, Nov 14, 2009 at 1:43 PM, Stephen Nelson-Smith
<sanelson at gmail.com> wrote:
> Hi,
>> I'm not 100% sure to understand your needs and intention; just have a try. Maybe what you want actually is rather:
>>
>> for log in logs:
>> for line in log:
>> print l
>
> Assuming you meant print line. This also gives me just three lines.
>
>> Meaning your log objects need be iterable. To do this, you must have an __iter__ method that would surely simply return the object's getline (or maybe replace it alltogether).
>
> I'm not sure I fully understand how that works, but yes, I created an
> __iter__ method:
>
> def __iter__(self):
> self.line=self.logfile.readline()
> stamp=self.timestamp(self.line)
> heapq.heappush(self.heap, (stamp, self.line))
> pop = heapq.heappop(self.heap)
> yield pop
>
> But I still don't see how I can iterate over it... I must be missing something.
>
> I thought that perhaps I could make a generator function:
>
> singly = ((x.stamp, x.line) for x in logs)
> for l in singly:
> print
>
> But this doesn't seem to help either.
>
>
>> Then when walking the log with for...in, python will silently call getline until error. This means getline must raise StopIteration when the log is "empty" and __iter__ must "reset" it.
>
> Yes, but for how long? Having added the __iter__ method, if I now do:
>
> for log in logs:
> for line in log:
> print line
>
> I still get only three results.
>
>> Another solution may be to subtype "file", for a file is precisely an iterator over lines; and you really get your data from a file.
>
> I'm very sorry - I'm not sure I understand. I get that a file is
> iterable by definition, but I'm not sure how subtyping it helps.
>
>> Simply (sic), there must some job done about this issue of time stamps (haven't studied in details). Still, i guess this track may be worth an little study.
>
> Sorry for not understanding :(
>
>> Once you get logs iterable, you may subtype list for your overall log collection and set it an __iter__ method like:
>>
>> for log in self:
>> for line in log:
>> yield line
>>
>> (The trick is not from me.)
>
> OK - I make the logs iterable by giving them an __iter__ method - I
> get that. I just don't know what you mean by 'subtype list'.
>
>> Then you can write:
>> for line in my_log_collection
>
> That sounds useful....
>
> S.
>
--
Stephen Nelson-Smith
Technical Director
Atalanta Systems Ltd
www.atalanta-systems.com
More information about the Tutor
mailing list