How does the destructor method __del__() work in Python?

PythonServer Side ProgrammingProgramming

The __del__() method is a known as a destructor method. It is called when an object is garbage collected which happens after all references to the object have been deleted.

In a simple case this could be right after you delete a variable like del x or, if x is a local variable, after the function ends. In particular, unless there are circular references, CPython  which is the standard Python implementation will garbage collect immediately.

The only property of Python garbage collection is that it happens after all references have been deleted, so this might not necessarily happen right after and even might not happen at all.

Even more so, variables can live for a long time for many reasons, for example. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of circular references — CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.

There are valid use cases for __del__: for example, 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 a required cleanup, you might want to call it directly, x.__del__(). 

Updated on 30-Jul-2019 22:30:21