Turning a file-like object into a true file object

Michael Kent mrmakent at cox.net
Mon May 26 10:33:22 EDT 2003


I'm working on a project for a special-purpose web robot, which I'm
discussing on my weblog (http://radio.weblogs.com/0124960).  As part
of that, I found I had the need to pass a file-like object to a method
(written by others) that would only accept a true file object (lesson:
unless you REALLY need your methods to only accept a true file object,
make them accept file-like objects).  This method was from a Python
extension written by C, so changing that method to accept a file-like
object was not feasable.  So I used the Adapter Pattern to come up
with this:

<pre>
import types
import os

class FileAdaptor:
    """A FileAdaptor instance takes a 'file-like' object having at
least a 'read' method
    and, via the file method, returns a true file object."""
    def __init__(self, fileObj):
        self.fileObj = fileObj
        self.chunksize = 1024 * 10

        if type(self.fileObj) != types.FileType:
            if not hasattr(fileObj, "read"):
                raise ValueError, "not a file-like object"
            
            self.tmpFileObj = os.tmpfile()
            while True:
                data = fileObj.read(self.chunksize)
                if len(data) == 0:
                    break
                self.tmpFileObj.write(data)

            del data                
            self.tmpFileObj.flush()
            self.tmpFileObj.seek(0, 0)

            self.fileObj = self.tmpFileObj                
        return

    def file(self):
        return self.fileObj
</pre>

Comments?  Is there a better way?




More information about the Python-list mailing list