# refcount.py # Don't try these tricks with plain ints/strings: they get # special handling. import sys class C: def __del__(self): print "Bye-bye!" # Two refcounts, because getrefcount() creates a reference a = C() print "References to a:", sys.getrefcount(a) b = c = d = a print "References to a:", sys.getrefcount(a) del b del c print "References to a:", sys.getrefcount(a) d = 1 print "References to a:", sys.getrefcount(a) # Object vanishes, calling __del__() del a import gc gc.disable() gc.set_debug(gc.DEBUG_SAVEALL) # Can't demo GC with __del__() class C: pass # Create a cycle a = C() b = C() a.b = b b.a = a del a del b gc.collect() print gc.garbage # Break cycle -- don't rely on this ordering in real life! del gc.garbage[1].b # Need to reap the references in gc.garbage, too del gc.garbage[:] gc.collect() print gc.garbage