Reliably call code after object no longer exists or is "unreachable"?

Thomas 'PointedEars' Lahn PointedEars at
Wed Apr 27 20:54:35 EDT 2011

Jack Bates wrote:

> Python's __del__ or destructor method works (above) - but only in the
> absence of reference cycles (below). An object, with a __del__ method,
> in a reference cycle, causes all objects in the cycle to be
> "uncollectable". This can cause memory leaks and because the object is
> never collected, its __del__ method is never called

AIUI there is no guarantee that __del__() will be called automatically at 


> Faced with the real potential for reference cycles, how can you reliably
> call code - but wait until an object no longer exists or is
> "unreachable"?

For normal program termination, the solution is the `atexit' module (as used 
e.g. in <
management-with-autoclose/>, however it is considered better style to 
explicitly call methods that free resources, and `del' object references.

As for abnormal program termination, I think there is no way to deal with 
signals that signal.signal() cannot handle.


More information about the Python-list mailing list