I find that custom __del__
method seems not to execute when circular referencing are involved.
Here is a sample code:
class DelClass():
def __init__(self,a):
self.prop = a
def __del__(self):
print 'del'
if __name__ == "__main__":
dc1 = DelClass(None)
dc2 = DelClass(dc1)#dc2 referring to dc1
dc1.prop = dc2#dc1 referring to dc2, thus creating circular reference
del dc1#not executing the custom __del__ method
dc = DelClass(1)
del dc#executing the custom __del__ method
Why this happens?
Edit: Thanks to BrenBarn. I found the reason.
del something
only decrements the reference count of something
by 1.
__del__
will only execute when the reference count reaches 0.
Here is a test code:
import gc
class DelClass():
def __init__(self,name,a):
self.name = name
self.prop = a
def __del__(self):
print '#####deleting',self.name
dc1 = DelClass("dc1",None)
dc2 = DelClass("dc2",dc1)#dc2 referring to dc1
dc1.prop = dc2#dc1 referring to dc2, thus creating circular reference
print "before deleting dc1,reference count:",len(gc.get_referrers(dc1))
del dc1#not executing the custom __del__ method
print "after deleting dc1, reference count:",len(gc.get_referrers(dc2.prop))
print "deleting the reference held by dc2"
del dc2.prop
print dc2
The output is:
before deleting dc1,reference count: 2
after deleting dc1, reference count: 1
deleting the reference held by dc2
#####deleting dc1
<__main__.DelClass instance at 0x9316dec>
#####deleting dc2
And another question appears:
why the last line(#####deleting dc2
) in the output happens?
Some implicit del
operation happens?