I wanted to be able to get a tuple of references to any existing object instances of a class. What I came up with was:
import gc
def instances(theClass):
When you work in interactive mode, there's a magic built-in variable _ that holds the result of the last expression statement you ran:
>>> 3 + 4
7
>>> _
7
When you delete the c variable, del c isn't an expression, so _ is unchanged:
>>> c = MyClass()
>>> instances(MyClass)
(<__main__.MyClass object at 0x00000000022E1748>,)
>>> del c
>>> _
(<__main__.MyClass object at 0x00000000022E1748>,)
_ is keeping a reference to the MyClass instance. When you call gc.collect(), that's an expression, so the return value of gc.collect() replaces the old value of _, and c finally gets collected. It doesn't have anything to do with the garbage collector; any expression would do:
>>> 4
4
>>> instances(MyClass)
()