[Tutor] deriving class from file to handle input line numbers?

Andreas Kostyrka andreas at kostyrka.org
Thu Aug 18 10:10:51 CEST 2005

My try at this problem:

# filecounter.py:
#!/usr/bin/env python

class CountedFile(file):
    def __init__(self, *args, **kw):
        self.linecount = 0
        super(CountedFile, self).__init__(*args, **kw)

    def read(self, *args):
        data = super(CountedFile, self).read(*args)
        self.linecount += data.count("\n")
        return data

    def readline(self, *args):
        data = super(CountedFile, self).readline(*args)
        self.linecount += data.count("\n")
        return data

    def next(self):
        data = super(CountedFile, self).next()
        self.linecount += data.count("\n")
        return data

if __name__ == "__main__":
    f = CountedFile("filecounter.py")
    print f.linecount
    for x in f:
        print "%3d: %s" % (f.linecount, x.rstrip())

Only drawback: It cannot be used for already open files, like sys.stdin.
For these a delegation based solution (which probably could be coded up with __getattr__)
seems plausible.

One explanation: One needs to reimplement all reading interfaces, because readline doesn't use an
overridden read method.


Am Dienstag, den 16.08.2005, 15:35 +0200 schrieb Duncan Gibson:
> I wrote:
> > >     class MyFile(file):
> > >         etc
> > > 
> > > I couldn't see how to have an instance of MyFile returned from the
> > > built-in 'open' function. I thought this was the crux of the problem.
> Kent Johnson replied:
> > open() is actually just an alias for file():
> >  >>> open is file
> > True
> Thank you very much! You have just provided me with the vital piece of
> information I needed and everything has just clicked into place.
> Now that I know that I've searched the documentation again and found:
>     The file() constructor is new in Python 2.2 and is an alias for
>     open(). Both spellings are equivalent. The intent is for open()
>     to continue to be preferred for use as a factory function which
>     returns a new file object. The spelling, file is more suited to
>     type testing (for example, writing "isinstance(f, file)").
> See http://docs.python.org/lib/built-in-funcs.html#l2h-25
> Cheers
> Duncan
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20050818/1c30f8a3/attachment-0001.pgp

More information about the Tutor mailing list