I've got a class that wraps some file handling functionality I need. Another class creates an instance of the filehandler
and uses it for an indeterminate amount of time. Eventually, the caller
is destroyed, which destroys the only reference to the filehandler
.
What is the best way to have the filehandler
close the file?
I currently use __del__(self)
but after seeing several different questions and articles, I'm under the impression this is considered a bad thing.
class fileHandler:
def __init__(self, dbf):
self.logger = logging.getLogger('fileHandler')
self.thefile = open(dbf, 'rb')
def __del__(self):
self.thefile.close()
That's the relevent bit of the handler. The whole point of the class is to abstract away details of working with the underlying file object, and also to avoid reading the entire file into memory unnecessarily. However, part of handling the underlying file is closing it when the object falls out of scope.
The caller
is not supposed to know or care about the details involved in the filehandler
. It is the filehandler
's job to release any necessary resources involved when it falls out of scope. That's one of the reasons it was abstracted in the first place. So, I seem to be faced with moving the filehandler
code into the calling object, or dealing with a leaky abstraction.
Thoughts?