Why do I have to call del explicitly for com objects?

Gabriel Genellina gagsl-py at yahoo.com.ar
Fri Jan 19 11:05:46 EST 2007


<bg_ie at yahoo.com> escribió en el mensaje 
news:1169210578.544593.310100 at v45g2000cwv.googlegroups.com...

> I'm creating objects in my python script belonging to a COM object
> which I dispatch using win32com.client.DispatchEx. Hence, dllhost.dll
> is the concerned process. The problem is that the objects destructor
> within the com object is not called if the object lives past a certain
> number of seconds. For example, this function will not call the
> destructor concerned with obj unless the sleep is commented out.
>
> def fnction:
>  obj = comobj.createACertainObject()
>  obj.doStuff()
>  sleep(10)
>  obj.doMoreStuff()
>  #del obj

I don't understand the case.
del does not invoke a destructor, just decrements the object's reference 
count. When the rc reaches zero, the object is a candidate for GC. That is, 
"some time in the future", the GC would destroy it (unless it's part of a 
circular reference chain...)
So, *inside* your function, there is a reference held by the local variable 
obj. It is decremented automatically when you exit the function (and obj 
gets out of scope) or if you explicitely use del.
You can use sys.getrefcount() to see how many references an object has. (The 
output is +1 because getrefcount() has a temporary reference to the object 
too).

py> x="Hello World"
py> sys.getrefcount(x)
2

See how many references your obj have. After calling doStuff or doMoreStuff, 
you can have more references if those functions store `self` somewhere, or 
pass it to another method that does so.

> It seems to me that the GC forgets about obj after a certain amount of
> time. I can force the destructor to be called using del obj at the end
> of my function, but why do I have to call this explicitly?
If del obj works at the end, exiting the function should work too. Both ways 
you decrement the rc. There is something *more* in here.

-- 
Gabriel Genellina 





More information about the Python-list mailing list