__del__ doesn't work

Josiah Carlson jcarlson at nospam.uci.edu
Mon Feb 16 01:06:39 EST 2004


> I don't believe that Python can cope with this and the object
> will never actually be deleted. Please correct me if I am wrong.

You are incorrect.

 From http://www.python.org/doc/current/lib/module-gc.html:
"The gc module is only available if the interpreter was built with the 
optional cyclic garbage detector (enabled by default). If this was not 
enabled, an ImportError is raised by attempts to import this module."

It is enabled in Windows builds, and I believe it is also enabled in all 
other distributed builds.

In general, cycle detection is costly, and is only done when a large 
amount of memory is being used.


> In certain circumstances where I have had this problem and I
> needed to know the object would be destroyed as soon as
> possible, I have had to add a method to the class which could
> be called to undo any references the class held which pointed
> back onto itself.

That is smart, but it does beg the question: Why would a class instance 
need to have a reference to itself?  I can understand certain reasons, 
but many can be translated into weakrefs with little difficulty.


> I have looked at weak references, but have not been satisfied
> that it could be used in the situation where I had to overcome the
> problem.

Weak referenced objects are not required to be deleted immediately 
following the final strong reference removal.  Perhaps that is where 
your confusion lies.

Nowhere does it claim to delete immediately following the final strong 
reference removal, the garbage collector collects when it is ready to. 
One thing to remember is that sometimes references hide.

 >>> import weakref
 >>> class thing(object):
...     def __init__(self):
...         print "init"
...         self.me = weakref.ref(self)
...     def __del__(self):
...         print "del"
...
 >>> a = thing()
init
 >>> del a
del
 >>> a = thing()
init
 >>> a
<__main__.thing object at 0x007E4D70>
 >>> del a
 >>> a
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
NameError: name 'a' is not defined
 >>> "I wonder why a hasn't been deleted yet..."
del
"I wonder why a hasn't been deleted yet..."
 >>> "Ahhh", _
('Ahhh', "I wonder why a hasn't been deleted yet...")


  - Josiah



More information about the Python-list mailing list