subclassing file objects (to extend open and close operations) in python 3

python, python-3.x

Solution

You could just use a context manager instead. For example this one:

class SpecialFileOpener:
    def __init__ (self, fileName, someOtherParameter):
        self.f = open(fileName)
        # do more stuff
        print(someOtherParameter)
    def __enter__ (self):
        return self.f
    def __exit__ (self, exc_type, exc_value, traceback):
        self.f.close()
        # do more stuff
        print('Everything is over.')

Then you can use it like this:

>>> with SpecialFileOpener('C:\\test.txt', 'Hello world!') as f:
        print(f.read())

Hello world!
foo bar
Everything is over.

Using a context block with `with` is preferred for file objects (and other resources) anyway.

Problem

Suppose I want to extend the built-in file abstraction with extra operations at `open` and `close` time. In Python 2.7 this works: ``` class ExtFile(file): def __init__(self, *args): file.__init__(self, *args) # extra stuff here def close(self): file.close(self) # extra stuff here ``` Now I'm looking at updating the program to Python 3, in which `open` is a factory function that might return an instance of any of several different classes from the `io` module depending on how it's called. I could in principle subclass all of them, but that's tedious, and I'd have to reimplement the dispatching that `open` does. (In Python 3 the distinction between binary and text files matters rather more than it does in 2.x, and I need both.) These objects are going to be passed to library code that might do just about anything with them, so the idiom of making a "file-like" duck-typed class that wraps the return value of `open` and forwards necessary methods will be most verbose. Can anyone suggest a 3.x approach that involves as little additional boilerplate as possible beyond the 2.x code shown?

Original source