How to overide "for line in file:"

Peter Otten __peter__ at web.de
Sun Feb 22 04:07:22 EST 2004


David Morgenthaler wrote:

> How does one overide the iterator implied by the construct "for line
> in file:"?
> 
> 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):
> 
> class myFile(file):
>     def __init__(self,name,affine):
>         self.affine = affine
>         file.__init__(name)
> 
>     def next(self):
>         for line in file.__iter__(self):
>             r,c = ",".split(line[:-1]
>             yield self.affine(r,c)

Here are two ways to make the above work:

# add an additional iterator
class myFile(file):
    def __init__(self, name, affine):
        self.affine = affine
        file.__init__(self, name) # oops, self was missing

    def pairs(self): #oops, name clash
        for line in self:
            r,c = line[:-1].split(",") #oops, wrong use of split()
            yield self.affine(r,c)

# change the original iterator's behaviour
class myFile2(file):
    def __init__(self, name, affine):
        self.affine = affine
        file.__init__(self, name)

    def next(self):
        line = file.next(self)
        r, c = line[:-1].split(",")
        return self.affine(r,c)

#create sample data
r = iter(range(10))
sample = "".join(["%d,%d\n" % (i,j) for (i,j) in zip(r,r)])
file("tmp.txt", "w").write(sample)

def op(a, b):
    return int(a)*int(b)

for v in myFile("tmp.txt", op).pairs():
    print v,
print

for v in myFile2("tmp.txt", op):
    print v,
print


Peter




More information about the Python-list mailing list