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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With