link text
I got the concept of reference count
So when i do a \"del astrd\" ,reference count drops to zero and astrd gets collected by gc ?
This is t
I believe that memory is automatically freed the moment the refcount reaches zero. The GC is not involved.
The python GC is optional, and is only used when there are unreachable objects that has reference cycles. In fact, you can call gc.disable()
if you are sure your program does not create reference cycles.
As for the original question:
del astrd
, you remove the binding of astrd from the local namespace a reference to an object (whatever astrd references).del
does not delete objects, it unbinds references. The deletion of objects is a side effect that occurs if unbinding a reference causes the refcount to reach zero.Note that the above is only true for CPython. Jython and IronPython uses the JVM/CLR GC mechanism, and does not use refcounting at all, I believe.
The handy gc.get_objects
returns a list of all object instances tracked by the python interpreter. Example:
import gc class test(object): pass def number_of_test_instances(): return len([obj for obj in gc.get_objects() if isinstance(obj, test)]) for i in range(100): t = test() print "Created and abandoned 100 instances, there are now", \ number_of_test_instances(), \ "instances known to the python interpreter." # note that in normal operation, the GC would # detect the unreachable objects and start # collecting them right away gc.disable() for i in range(100): t = test() t.t = t print "Created and abandoned 100 instances with circular ref, there are now", \ number_of_test_instances(), \ "instances known to the python interpreter." gc.collect() print "After manually doing gc.collect(), there are now", \ number_of_test_instances(), \ "instances known to the python interpreter."
Running this program gives:
Created and abandoned 100 instances, there are now 1 instances known to the python interpreter. Created and abandoned 100 instances with circular ref, there are now 100 instances known to the python interpreter. After manually doing gc.collect(), there are now 1 instances known to the python interpreter.