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 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
. However, a group
of objects can also be unreachable when they reference each other.
Classic
Python keeps in 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, rely on different garbage
collection mechanisms, supplied by the platform they run on (e.g.,
the JVM). 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
to other objects, Python removes the references, which in turn may
make other objects collectable by leaving them unreachable.
The gc Module
The ...
Get Python in a Nutshell 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.