How do I override file.write() under Python 3?

Posted by Sorin Sbarnea on Stack Overflow See other posts from Stack Overflow or by Sorin Sbarnea
Published on 2010-06-15T14:23:15Z Indexed on 2010/06/15 15:52 UTC
Read the original article Hit count: 171

Filed under:

Below works on Python 2.6 but on Python 3.x it doesn't:

old_file_write = file.write 

class file():
    def write(self, d):
        if isinstance(d, types.bytes):
            self.buffer.write(d)
        else:
            old_file_write(d)

# ... do something like f = open("x") f.write("...")

The problems is that with Python 3.x the first like will generate an error:

NameError: name 'file' is not defined

How can I make this work on Python 3.x?

PS. In fact I'm looking for a solution that will work on both versions.

© Stack Overflow or respective owner

Related posts about python-3.x