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

Kent Johnson kent37 at tds.net
Tue Aug 16 15:06:10 CEST 2005

Duncan Gibson wrote:
> Kent Johnson wrote:
> To be perfectly honest, I didn't try it because even if I had declared
>     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.

open() is actually just an alias for file():
 >>> open is file

But if you have your own file class then you will call it's constructor rather than open(). Here is a simple example:

 >>> class MyFile(file):
 ...   def __init__(self, *args, **kwds):
 ...     self.lineNumber = 0
 ...     super(MyFile, self).__init__(*args, **kwds)
 ...   def readline(self):
 ...     self.lineNumber += 1
 ...     return super(MyFile, self).readline()
 >>> f=MyFile('build.xml')
 >>> f.lineNumber
 >>> f.readline()
'<?xml version="1.0"?>\n'
 >>> f.lineNumber
 >>> f.readline()
 >>> f.lineNumber

> So what I have done is provide a different interface completely,
>     class MyFile(object):
>         etc
> I could extend this to take the file name in the constructor, and
> add a MyFile.open() method, but then I can no longer substitute
> any MyFile instances in places that expect 'file' instances.

Why not? You have to change the way you create the 'file', but once you have an instance it might work just fine.

Python has a concept of 'file-like object' - something that acts enough like a file to be usable in place of a file. In your case it might be enough to implement readline(), close() and __del__().
> Now that I've started to explain all of this to someone else, I'm
> starting to wonder whether it really matters. Do I really need it
> to be substitutable for 'file' after all ?

That depends on your usage. The only reason it would have to be substitutable for file is if you plan to pass MyFile instances to functions that expect file objects. If the only usage is in your code you have control over it and you can give MyFile whatever API you like.

In any event I think the simple file subclass above may meet your needs...


More information about the Tutor mailing list