The __del__() method
The __del__()
method has a rather obscure use case.
The intent is to give an object a chance to do any cleanup or finalization just before the object is removed from memory. This use case is handled much more cleanly by context manager objects and the with
statement. This is the subject of Chapter 5, Using Callables and Contexts. Creating a context is much more predictable than dealing with __del__()
and the Python garbage collection algorithm.
In the case where a Python object has a related OS resource, the __del__()
method is a last chance to cleanly disentangle the resource from the Python application. As examples, a Python object that conceals an open file, a mounted device, or perhaps a child subprocess might all benefit ...
Get Mastering Object-oriented Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.