Need help to understand garbage collection

  • Thread starter David Tremouilles
  • Start date
D

David Tremouilles

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'>]
***
 

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