Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

del MyClass doesn't call object.__del__()

I have a class that opens a file for writing. In my destructor, I call the function that closes the file:

class MyClass:
    def __del__(self):
        self.close()

    def close(self):
        if self.__fileHandle__ is not None:
                self.__fileHandle__.close()

but when I delete the object with code like:

myobj = MyClass()
myobj.open()
del myobj

if I try to reinstantiate the object, I get a value error:

ValueError: The file 'filename' is already opened.  Please close it before reopening in write mode.

whereas if I call myobj.close() before del myobj I don't get this problem. So why isn't __del__() getting called?

like image 621
tdc Avatar asked Jan 18 '12 09:01

tdc


1 Answers

Are you sure you want to use __del__? There are issues with __del__ and garbage collection.

You could make MyClass a context manager instead:

class MyClass(object):
    def __enter__(self):
        return self
    def __exit__(self,ext_type,exc_value,traceback):
        if self.__fileHandle__ is not None:
                self.__fileHandle__.close()

By doing so, you could use MyClass like this:

with MyClass() as myobj:
    ...

and myobj.__exit__ (and thus self.__fileHandle__.close()) will be called when Python leaves the with-block.

like image 169
unutbu Avatar answered Sep 27 '22 23:09

unutbu