How soon after the reference count reaches zero is __del__
method called? Does the language promise that it\'s done right away, before any other use code can ex
About the only reason you should ever use __del__
is to help the garbage collector collect more garbage. For instance, if you are implementing something like the ctypes
module that attaches shared libraries to the running process, it makes sense to unload those libraries when the last reference to it is collected, to allow its address space to be used for something else.
For managing other kinds of resources, you almost certainly don't want to have anything to do with the garbage collector. The correct tool for this is context managers. Unlike languages such as C++ or Ada where variable scope is used for RAII, python uses the with
statement, along with an object that has an __enter__
and __exit__
method. Many built in python types use this exact mechanism to make sure finalization steps actually occur:
>>> x = file("foo", 'w')
>>> x.closed
False
>>> with x:
... x.write("bar")
...
>>> x.closed
True
This is also valuable from the point of view of the zen of python:
Explicit is better than implicit.
because it is clear that cleanup is occuring, it is explicitly written that way. This is much better than the case of cleanup happening "magically" when some hidden variable (the reference count, if one exists, and it doesn't in PyPy or IronPython or Jython) reaches some particular value, maybe.