How to subclass file

Yves Dorfsman yves at zioup.com
Wed May 14 20:23:26 EDT 2008


I want to create a subclass of 'file' but need to open the file with os.open
(because I want to open it in exclusive mode), and need an additional method.

Because I need an additional method, I truly need a object of my sublass.
If I do something like

class myFile(file):

  def __new__(cls, filename):
    import os
    fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
 
    return os.fdoen(fd, 'w')

  def myMethod(self):
    do_something


then x = myFile('somefilename') is of type file, not myFile, and therefore
does not have myMethod as a valid method.

Now if I try:

class myFile(file):

  def __new__(cls, filename):
    import os
    fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)

    obj = file.__new__(cls)
 
    return obj

  def myMethod(self):
    do_something

Then it fails, because the 'file' constructor needs a filename. I can provide
the filename, but it will then try to re-open that file, and even if I did
manage to create an object file, how do I connect the file descriptor created
by os.open to my object ?


Thanks.


Yves.
http://www.SollerS.ca




More information about the Python-list mailing list