Python’s garbage collection normally proceeds transparently and automatically, but you can choose to exert some direct control. The general principle is that Python collects each object
x at some time after
x becomes unreachable—that is, when no chain of references can reach
x by starting from a local variable of a function instance that is executing, nor from a global variable of a loaded module. Normally, an object
x becomes unreachable when there are no references at all to
x. In addition, a group of objects can be unreachable when they reference each other but no global nor local variables reference any of them, even indirectly (such a situation is known as a mutual reference loop).
Classic Python keeps with each object
x a count, known as a reference count, of how many references to
x are outstanding. When
x’s reference count drops to
0, CPython immediately collects
getrefcount of module
sys accepts any object and returns its reference count (at least
getrefcount itself has a reference to the object it’s examining). Other versions of Python, such as Jython or IronPython, rely on other garbage-collection mechanisms supplied by the platform they run on (e.g., the JVM or the MSCLR). Modules
weakref therefore apply only to CPython.
When Python garbage-collects
x and there are no references at all to
x, Python then finalizes
x (i.e., calls
._ _del_ _( )) and makes the memory that
x occupied available for other uses. If
x held any references ...