How to overide "for line in file:"

Shalabh Chaturvedi shalabh at cafepy.com
Sun Feb 22 04:03:57 EST 2004


David Morgenthaler wrote:

> 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

Did you mean myfile.xreadlines()? In which case your code is quite correct.
You could even get rid of the .xreadlines() part and have it work the 'new'
way (and identical to what Terry Reedy suggested :).

Now I'm not sure what you want but note that the example from Terry Reedy
does not have a 'list of lines' - lines is an iterable, which means it
could be a file object. So, you could call that example as:

for x,y in xycoords(file('..')):
    <do something>

Now, each time the above for loops once, the for inside xycoords() loops
once. There is never a list of lines created anywhere.

HTH,
Shalabh



More information about the Python-list mailing list