Garbage Collection
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 x
. Function getrefcount
of module sys
accepts any object and returns its reference count (at least 1
, since 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 gc
and 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 x
._ _del_ _( )
) and makes the memory that x
occupied available for other uses. If x
held any references ...
Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.