The gc module is only available if the interpreter was built with the optional cyclic garbage detector (enabled by default). If this was not enabled, an ImportError is raised by attempts to import this module.
This module provides an interface to the optional garbage collector. It
provides the ability to disable the collector, tune the collection
frequency, and set debugging options. It also provides access to
unreachable objects that the collector found but cannot free. Since the
collector supplements the reference counting already used in Python, you
can disable the collector if you are sure your program does not create
reference cycles. Automatic collection can be disabled by calling
gc.disable()
. To debug a leaking program call
gc.set_debug(gc.DEBUG_LEAK)
.
The gc module provides the following functions:
sys.stderr
. See below
for a list of debugging flags which can be combined using bit
operations to control debugging.
The GC classifies objects into three generations depending on how many
collection sweeps they have survived. New objects are placed in the
youngest generation (generation 0
). If an object survives a
collection it is moved into the next older generation. Since
generation 2
is the oldest generation, objects in that
generation remain there after a collection. In order to decide when
to run, the collector keeps track of the number object allocations and
deallocations since the last collection. When the number of
allocations minus the number of deallocations exceeds
threshold0, collection starts. Initially only generation
0
is examined. If generation 0
has been examined more
than threshold1 times since generation 1
has been
examined, then generation 1
is examined as well. Similarly,
threshold2 controls the number of collections of generation
1
before collecting generation 2
.
(threshold0, threshold1, threshold2)
.
The following variable is provided for read-only access:
The following constants are provided for use with set_debug():
garbage
list.
DEBUG_COLLECTABLE |
DEBUG_UNCOLLECTABLE | DEBUG_INSTANCES | DEBUG_OBJECTS | DEBUG_SAVEALL
).