Problems when destroy object which is referenced member objects

M

Minkyu Kim

Hi.
Please check this simple test code.

---------------------
class TestA:
def __init__(self):
print "init TestA"
def __del__(self):
print "del TestA"
def SetEvent(self, event):
self.event = event

class TestB:
def __init__(self):
print "init TestB"
self.testA = TestA()
self.testA.SetEvent(self.Test)
def __del__(self):
print "del TestB"
def Test(self):
pass

testB = TestB()
del testB
---------------------

I want to run this code that destroy testB and testB's member object
testA. But no object destroy. I know testA increase testB's reference
count, but why wouldn't python decrease testB's reference count? Had I
do wrong something?
 
T

Terry Reedy

class TestA:
def __init__(self):
print "init TestA"
def __del__(self):
print "del TestA"
def SetEvent(self, event):
self.event = event

class TestB:
def __init__(self):
print "init TestB"
self.testA = TestA()
self.testA.SetEvent(self.Test)
def __del__(self):
print "del TestB"
def Test(self):
pass

testB = TestB()
del testB
---------------------

I want to run this code that destroy testB and testB's member object
testA. But no object destroy. I know testA increase testB's reference
count, but why wouldn't python decrease testB's reference count? Had I
do wrong something?

You created a circular reference loop of objects with __del__ methods.
Without adding 'del testB.testA' to break the loop, before the testB
deletion, the reference counts never go to 0.

I believe the gc garbage collector will also leave the loop alone because
of the __del__ methods. Trying to watch gc in action stops it (!) because
__del__ methods can do (and have done) things that mess up the gc process,
so gc no longer tries when they are present. So break the loop as
indicated above.

Terry J. Reedy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top