Class destructor

Roberto Cavada cavada at
Thu Feb 13 15:46:03 CET 2003

Hi there,
  suppose you wrote this class definition:

class A:
     def __init__(self):
         self.ref = self
         print "Built instance of A"

     def __del__(self):
         print "Destroying instance of A"

     pass # end of class

a1 = A()
del a1  # This does not call A.__del__

a2 = A()
del a2.ref # Neither does this
del a2  # This calls it

Yap, this behaviour is well-documented, and about circular references 
the documentation states that:
"Circular references which are garbage are detected when the option 
cycle detector is enabled (it's on by default), but can only be 
cleaned up if there are no Python-level __del__() methods involved. 
Refer to the documentation for the gc module for more information 
about how __del__() methods are handled by the cycle detector, 
particularly the description of the garbage value."

If I correctly understood, circular references detection is disabled 
when __del__ method is defined. I guess this is a precise choice, due 
to the fact that there is no control on what __del__ really does, so 
it is better wasting of memory than falling into segfaults.

If it is correct, I think this is a strong restriction, because I 
cannot control the lifetime of instances.

What's the solution in this case?

Roberto Cavada
ITC-irst Institute for Scientific and Technological Research
Automated Reasoning Systems - Formal Methods Group
Via Sommarive, 18 - 38050 Povo (TN) - Italy
Tel: +39 0461 314 321   Fax: +39 0461 302 040
cavada at

More information about the Python-list mailing list