It is __del__ calling twice for some instances?

Duncan Booth duncan.booth at invalid.invalid
Fri Aug 18 05:01:31 EDT 2006


Duncan Booth wrote:

> As to why it happens, there is a mechanism in Python to stop unlimited
> stack being used when objects are freed: when the stack gets too deep
> then instead of being released, the Py_DECREF call puts the object
> into a trashcan list and the objects aren't released until the stack
> has unwound. It looks like there must be a bug round the trashcan
> mechanism somewhere. 

I figured out what is going on in the code to deallocate an old-style class 
instance:

The reference count is temporarily incremented.

If the class has a __del__ method then a descriptor is created for the 
method and called. When the call returns, the descriptor is released.

Then the object itself is released using special code to avoid a recursive 
call to the deallocator.

However, if the trashcan mechanism is invoked by the attempt to release the 
descriptor, it actually queues the descriptor in the trashcan. Since the 
descriptor contains a reference to the object it has effectively 
resurrected it. This means the special code to avoid the recursive call 
simply decrements the reference count but does not release anything (the 
object has been resurrected by the descriptor). When the descriptor is 
later released the __del__ method is triggered a second time.



More information about the Python-list mailing list