How do you use weakref or contextlib to close open files?
<p>I have a class that holds a strong reference to an open file. If the code runs without any exceptions then the file is closed correctly, because I explicitly call a method on the class that closes the file. However, if an exception is thrown then, the file is not closed correctly.</p>

<p>Here is a mocked up version of my code:</p>

<pre><code>class MyFile(object):
    def __init__(self, filename, mode):
        self._handle = open(filename, mode)

    @classmethod
    def open(cls, filename, mode):
        return MyFile(filename, mode)

    def close(self):
        self._handle.close()

    def __del__(self):
        self.close()

    def writerow(data):
        # Special write
        pass

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        self.close()
</code></pre>

<p>Now if I were using this class at the top level of my code I would use a with statement:</p>

<pre><code>def get_some_dat():
    return 1

with MyFile.open('foo.txt', 'w') as f:
    # do stuff with f
    data = get_some_data()
    f.writerow(data)
</code></pre>

<p>However, MyFile is opened indirectly by another object. I know that most Pythonistas will say that I should explicitly close the file, but I would like to make sure that the file is closed when the object is destroyed. The code that I've written will do the trick, but I was wondering if anyone had suggestions on a better way of implementing this behavior.</p>
