Need help to understand garbage collection

David Tremouilles david.trem at gmail.com
Sun Oct 7 03:25:55 EDT 2007


Thanks Gabriel!
I get it now. With your help I was able to focus on the real problem.
Here is the correctly working example for the record:


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
del new_objects
del obj

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 = [idx for idx in original_objects_id
                   if idx not in after_rm_objects_id]
print "-" * 40
print "Removed objects:", len(removed_objects_id)
print removed_objects_id
print "-" * 20



More information about the Python-list mailing list