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

Thomas 'PointedEars' Lahn PointedEars at web.de
Thu Apr 28 02:54:35 CEST 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 
all:

<http://docs.python.org/reference/datamodel.html#object.__del__>

> 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 <http://code.activestate.com/recipes/523007-semi-automatic-resource-
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.


HTH
-- 
PointedEars



More information about the Python-list mailing list