ANN: experimental patch to allow importing from file-like objects

Hans Nowak wurmy at earthlink.net
Sat Mar 2 20:32:12 EST 2002


Gerson Kurz wrote:

> On a related note, (I've asked this before to no avail) - how do I
> successfully subclass files & open them?
> 
> The problem is - where to I subclass a file returned from open()?
> open() always returns the builtin file class. Attempting to do this
> 
> ----------- (snip here) -------------
> 
> raw_file = open(...)
> my_file = my_file_class()
> raw_file.read = my_file.read
> 
> ----------- (snip here) -------------
> 
> I'll get an error that read is a read-only method.

I don't know much about 2.2 yet, but I think the
preferred method is subclassing file, then opening a
file through the subclass's constructor (rather than
through open()). For example:

class NoisyFile(file):
    def __init__(self, *args, **kwargs):
        file.__init__(self, *args, **kwargs)
        print "Bwahahaha!"

f = NoisyFile("c:/python/test/2.2/test-file-1.py", "r")
print f.readlines()
f.close()

HTH,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) 
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/



More information about the Python-list mailing list