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.
Here is a mocked up version of my 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()
Now if I were using this class at the top level of my code I would use a with statement:
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)
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.
Here is an example using
weakrefto ensure that the file is closed, even if it is opened without using thewith ...syntax:prints
PS: I suspect that this code is not mine, but I’ve lost any reference to where it comes from. If someone knows, please tell so I can give proper attribution.