Class destructor

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Feb 14 04:15:53 EST 2003


Jp Calderone <exarkun at intarweb.us> wrote in 
news:mailman.1045165005.8890.python-list at python.org:

>> What's the solution in this case?
> 
>   There are several, at least.  In order of personal preference:
> 
>   1) Don't create cycles of objects that implement __del__.

In cases such as given by the OP it should be easy enough to refactor the 
code to remove the destructor from the class involved in the cycle:

>>> class A:
     class Destructor:
         def __del__(self):
             print "Destroying instance of A"
             return

     def __init__(self):
         self._destructor = A.Destructor()
         self.ref = self
         print "Built instance of A"
         return


     pass # end of class

>>> a1 = A()
Built instance of A
>>> del a1
>>> import gc
>>> gc.collect()
Destroying instance of A
2
>>> 

The Destructor object mustn't contain any cyclic references (such as 
referring back to A), but it can hold references to objects required in the 
cleanup as long as they don't refer back.

I'm not sure how much use all this is though, as there is no guarantee that 
the garbage collector will be called between losing the last reference and 
the program exiting, so there isn't really very much of use you can do in a 
__del__ method anyway.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list