I am reading a code. There is a class in which __del__
method is defined. I figured out that this method is used to destroy an instance of the class. However, I
__del__
is a finalizer. It is called when an object is garbage collected which happens at some point after all references to the object have been deleted.
In a simple case this could be right after you say del x
or, if x
is a local variable, after the function ends. In particular, unless there are circular references, CPython (the standard Python implementation) will garbage collect immediately.
However, this is an implementation detail of CPython. The only required property of Python garbage collection is that it happens after all references have been deleted, so this might not necessary happen right after and might not happen at all.
Even more, variables can live for a long time for many reasons, e.g. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of cycle of references — CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.
Since you have no guarantee it's executed, one should never put the code that you need to be run into __del__()
— instead, this code belongs to finally
clause of the try
block or to a context manager in a with
statement. However, there are valid use cases for __del__
: e.g. if an object X
references Y
and also keeps a copy of Y
reference in a global cache
(cache['X -> Y'] = Y
) then it would be polite for X.__del__
to also delete the cache entry.
If you know that the destructor provides (in violation of the above guideline) a required cleanup, you might want to call it directly, since there is nothing special about it as a method: x.__del__()
. Obviously, you should you do so only if you know that it doesn't mind to be called twice. Or, as a last resort, you can redefine this method using
type(x).__del__ = my_safe_cleanup_method