How to overide "for line in file:"

Terry Reedy tjreedy at udel.edu
Sat Feb 21 23:13:19 EST 2004


"John Roth" <newsgroups at jhrothjr.com> wrote in message
news:103g0mhgmfups16 at news.supernews.com...
>
> <David Morgenthaler> wrote in message
> news:tisf301qf76c8lh0jkq9086gpqoep1bb1u at 4ax.com...
> > How does one overide the iterator implied by the construct "for line
> > in file:"?

Wrap it, don't replace it.  See below.

> > For example, suppose I have a file containing row,col pairs on each
> > line, and I wish to write a subclass of file that will transform these
> > to x,y coordinates using an affine transform. I'd like it to look
> > something like this (but this clearly doesn't work):

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.

Terry J. Reedy







More information about the Python-list mailing list