Need help to understand garbage collection
David Tremouilles
david.trem at gmail.com
Sat Oct 6 13:16:36 EDT 2007
I would need help to understand how garbage collection work and how to
"trace" objects...
In the example below an object is created and deleted.
Why in the second part of the example I do not see any object removed:
import gc
class Test(object):
def __init__(self):
pass
gc.collect()
original_objects_id = [id(x) for x in gc.get_objects()]
#create object a
a = Test()
gc.collect()
new_objects = [x for x in gc.get_objects()
if id(x) not in original_objects_id]
print "-" * 40
print "Added object:", len(new_objects)
for obj in new_objects:
print "*" * 10
print str(id(obj)) + ":" + str(obj)
print gc.get_referents(obj)
print "*" * 3
print "-" * 20
gc.collect()
original_objects_id = [id(x) for x in gc.get_objects()]
#remove object a
del a
gc.collect()
after_rm_objects_id = [id(x) for x in gc.get_objects()]
removed_objects_id = [x for x in original_objects_id
if x not in after_rm_objects_id]
print "-" * 40
print "Removed objects:", len(removed_objects_id)
print removed_objects_id
print "-" * 20
Which give:
----------------------------------------
Added object: 2
**********
400600:[[...], <__main__.Test object at 0x62bd0>]
[<__main__.Test object at 0x62bd0>, [[...], <__main__.Test object at 0x62bd0>]]
***
**********
404432:<__main__.Test object at 0x62bd0>
[<class '__main__.Test'>]
***
--------------------
----------------------------------------
Removed objects: 0
[]
--------------------
More information about the Python-list
mailing list