How to overide "for line in file:"
David
David
Sun Feb 22 02:27:11 EST 2004
On Sat, 21 Feb 2004 23:13:19 -0500, "Terry Reedy" <tjreedy at udel.edu>
wrote:
>Your class needs an __iter__ function. However, unless you have some other
>reason for the heavy duty class option, much easier is something like:
>
>def xycoords(lines):
> # lines is an iterable that yields text lines of appropriate format
> for line in lines:
> <extract numbers and transform>
> yield x,y
>
>You can feed xycoords a literal list of lines for testing and then an open
>file for production use.
>Chaining iterators like this is part of their intended use.
>
Hmmm. It was the "list of lines" that I was trying to avoid. Because
my files (several files, opened simultaneously) of row,col pairs are
very long (e.g., the locations of many things at every second for a
very long time), I was trying to get the effect of xreadlines, but
with the newer idiom used both "in and out" -- that is, used by the
super to actually read the data, and made available to myFile
instances as well. And since the only behavior of the file class that
I wanted to change was to, in effect, "filter" the input, subclassing
file seemed reasonable.
I could (in fact, I did, so as to not halt all progress) make a
solution using the even older "while True:/readline/test and break"
idiom. So I can use the idiom "outside" of my implementation. But my
curiosity remains: Is it possilbe to use the idiom "inside" (by the
super) to make the idiom available "outside" (by subclasses's
instances)?
Another poster has suggested that I subclass file and redefine
__iter__(self), possibly even point to self. The problem I have when
doing this is that it seems the break the idiom "for line in file"
that is provide by the superclass, file. And I would still like to use
this idiom for doing the actual reading within my .
So, what I was trying to achieve was something like the following
generator, but without the use of the deprecated xreadlines:
for line in xreadlines.xreadlines():
<extract numjber and transform>
yield x,y
Thanks, all, for your answers!
dave
More information about the Python-list
mailing list