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?
object- not doing so has been considered out-of-date style for some six years.myobj.close()changes things, without knowing what it does?deldoesn't call__del__. It just removes one of the references. Generally it's better to close explicitly, possibly using the context manager protocol (withstatement).