| 1 |
:mod:`!gc` --- Garbage Collector interface |
| 2 |
========================================== |
| 3 |
|
| 4 |
.. module:: gc |
| 5 |
:synopsis: Interface to the cycle-detecting garbage collector. |
| 6 |
|
| 7 |
.. moduleauthor:: Neil Schemenauer <[email protected]> |
| 8 |
.. sectionauthor:: Neil Schemenauer <[email protected]> |
| 9 |
|
| 10 |
-------------- |
| 11 |
|
| 12 |
This module provides an interface to the optional garbage collector. It |
| 13 |
provides the ability to disable the collector, tune the collection frequency, |
| 14 |
and set debugging options. It also provides access to unreachable objects that |
| 15 |
the collector found but cannot free. Since the collector supplements the |
| 16 |
reference counting already used in Python, you can disable the collector if you |
| 17 |
are sure your program does not create reference cycles. Automatic collection |
| 18 |
can be disabled by calling ``gc.disable()``. To debug a leaking program call |
| 19 |
``gc.set_debug(gc.DEBUG_LEAK)``. Notice that this includes |
| 20 |
``gc.DEBUG_SAVEALL``, causing garbage-collected objects to be saved in |
| 21 |
gc.garbage for inspection. |
| 22 |
|
| 23 |
The :mod:`!gc` module provides the following functions: |
| 24 |
|
| 25 |
|
| 26 |
.. function:: enable() |
| 27 |
|
| 28 |
Enable automatic garbage collection. |
| 29 |
|
| 30 |
|
| 31 |
.. function:: disable() |
| 32 |
|
| 33 |
Disable automatic garbage collection. |
| 34 |
|
| 35 |
|
| 36 |
.. function:: isenabled() |
| 37 |
|
| 38 |
Return ``True`` if automatic collection is enabled. |
| 39 |
|
| 40 |
|
| 41 |
.. function:: collect(generation=2) |
| 42 |
|
| 43 |
With no arguments, run a full collection. The optional argument *generation* |
| 44 |
may be an integer specifying which generation to collect (from 0 to 2). A |
| 45 |
:exc:`ValueError` is raised if the generation number is invalid. The sum of |
| 46 |
collected objects and uncollectable objects is returned. |
| 47 |
|
| 48 |
The free lists maintained for a number of built-in types are cleared |
| 49 |
whenever a full collection or collection of the highest generation (2) |
| 50 |
is run. Not all items in some free lists may be freed due to the |
| 51 |
particular implementation, in particular :class:`float`. |
| 52 |
|
| 53 |
The effect of calling ``gc.collect()`` while the interpreter is already |
| 54 |
performing a collection is undefined. |
| 55 |
|
| 56 |
.. versionchanged:: 3.14 |
| 57 |
``generation=1`` performs an increment of collection. |
| 58 |
|
| 59 |
.. versionchanged:: 3.14.5 |
| 60 |
``generation=1`` performs collection of the middle generation. |
| 61 |
|
| 62 |
|
| 63 |
.. function:: set_debug(flags) |
| 64 |
|
| 65 |
Set the garbage collection debugging flags. Debugging information will be |
| 66 |
written to ``sys.stderr``. See below for a list of debugging flags which can be |
| 67 |
combined using bit operations to control debugging. |
| 68 |
|
| 69 |
|
| 70 |
.. function:: get_debug() |
| 71 |
|
| 72 |
Return the debugging flags currently set. |
| 73 |
|
| 74 |
|
| 75 |
.. function:: get_objects(generation=None) |
| 76 |
|
| 77 |
Returns a list of all objects tracked by the collector, excluding the list |
| 78 |
returned. If *generation* is not ``None``, return only the objects tracked by |
| 79 |
the collector that are in that generation. |
| 80 |
|
| 81 |
.. versionchanged:: 3.8 |
| 82 |
New *generation* parameter. |
| 83 |
|
| 84 |
.. versionchanged:: 3.14 |
| 85 |
Generation 1 is removed |
| 86 |
|
| 87 |
.. versionchanged:: 3.14.5 |
| 88 |
Generation 1 is reintroduced to maintain GC behavior from 3.13. |
| 89 |
|
| 90 |
.. audit-event:: gc.get_objects generation gc.get_objects |
| 91 |
|
| 92 |
.. function:: get_stats() |
| 93 |
|
| 94 |
Return a list of three per-generation dictionaries containing collection |
| 95 |
statistics since interpreter start. The number of keys may change |
| 96 |
in the future, but currently each dictionary will contain the following |
| 97 |
items: |
| 98 |
|
| 99 |
* ``collections`` is the number of times this generation was collected; |
| 100 |
|
| 101 |
* ``collected`` is the total number of objects collected inside this |
| 102 |
generation; |
| 103 |
|
| 104 |
* ``uncollectable`` is the total number of objects which were found |
| 105 |
to be uncollectable (and were therefore moved to the :data:`garbage` |
| 106 |
list) inside this generation. |
| 107 |
|
| 108 |
.. versionadded:: 3.4 |
| 109 |
|
| 110 |
|
| 111 |
.. function:: set_threshold(threshold0, [threshold1, [threshold2]]) |
| 112 |
|
| 113 |
Set the garbage collection thresholds (the collection frequency). Setting |
| 114 |
*threshold0* to zero disables collection. |
| 115 |
|
| 116 |
The GC classifies objects into three generations depending on how many |
| 117 |
collection sweeps they have survived. New objects are placed in the youngest |
| 118 |
generation (generation ``0``). If an object survives a collection it is moved |
| 119 |
into the next older generation. Since generation ``2`` is the oldest |
| 120 |
generation, objects in that generation remain there after a collection. In |
| 121 |
order to decide when to run, the collector keeps track of the number object |
| 122 |
allocations and deallocations since the last collection. When the number of |
| 123 |
allocations minus the number of deallocations exceeds *threshold0*, collection |
| 124 |
starts. Initially only generation ``0`` is examined. If generation ``0`` has |
| 125 |
been examined more than *threshold1* times since generation ``1`` has been |
| 126 |
examined, then generation ``1`` is examined as well. |
| 127 |
With the third generation, things are a bit more complicated, |
| 128 |
see `Collecting the oldest generation <https://github.com/python/cpython/blob/ff0ef0a54bef26fc507fbf9b7a6009eb7d3f17f5/InternalDocs/garbage_collector.md#collecting-the-oldest-generation>`_ for more information. |
| 129 |
|
| 130 |
In the free-threaded build, the increase in process memory usage is also |
| 131 |
checked before running the collector. If the memory usage has not increased |
| 132 |
by 10% since the last collection and the net number of object allocations |
| 133 |
has not exceeded 40 times *threshold0*, the collection is not run. |
| 134 |
|
| 135 |
See `Garbage collector design <https://github.com/python/cpython/blob/3.14/InternalDocs/garbage_collector.md>`_ for more information. |
| 136 |
|
| 137 |
.. versionchanged:: 3.14 |
| 138 |
*threshold2* is ignored |
| 139 |
|
| 140 |
.. versionchanged:: 3.14.5 |
| 141 |
*threshold2* is restored to match Python 3.13 behavior. |
| 142 |
|
| 143 |
|
| 144 |
.. function:: get_count() |
| 145 |
|
| 146 |
Return the current collection counts as a tuple of ``(count0, count1, |
| 147 |
count2)``. |
| 148 |
|
| 149 |
|
| 150 |
.. function:: get_threshold() |
| 151 |
|
| 152 |
Return the current collection thresholds as a tuple of ``(threshold0, |
| 153 |
threshold1, threshold2)``. |
| 154 |
|
| 155 |
|
| 156 |
.. function:: get_referrers(*objs) |
| 157 |
|
| 158 |
Return the list of objects that directly refer to any of objs. This function |
| 159 |
will only locate those containers which support garbage collection; extension |
| 160 |
types which do refer to other objects but do not support garbage collection will |
| 161 |
not be found. |
| 162 |
|
| 163 |
Note that objects which have already been dereferenced, but which live in cycles |
| 164 |
and have not yet been collected by the garbage collector can be listed among the |
| 165 |
resulting referrers. To get only currently live objects, call :func:`collect` |
| 166 |
before calling :func:`get_referrers`. |
| 167 |
|
| 168 |
.. warning:: |
| 169 |
Care must be taken when using objects returned by :func:`get_referrers` because |
| 170 |
some of them could still be under construction and hence in a temporarily |
| 171 |
invalid state. Avoid using :func:`get_referrers` for any purpose other than |
| 172 |
debugging. |
| 173 |
|
| 174 |
.. audit-event:: gc.get_referrers objs gc.get_referrers |
| 175 |
|
| 176 |
|
| 177 |
.. function:: get_referents(*objs) |
| 178 |
|
| 179 |
Return a list of objects directly referred to by any of the arguments. The |
| 180 |
referents returned are those objects visited by the arguments' C-level |
| 181 |
:c:member:`~PyTypeObject.tp_traverse` methods (if any), and may not be all objects actually |
| 182 |
directly reachable. :c:member:`~PyTypeObject.tp_traverse` methods are supported only by objects |
| 183 |
that support garbage collection, and are only required to visit objects that may |
| 184 |
be involved in a cycle. So, for example, if an integer is directly reachable |
| 185 |
from an argument, that integer object may or may not appear in the result list. |
| 186 |
|
| 187 |
.. audit-event:: gc.get_referents objs gc.get_referents |
| 188 |
|
| 189 |
.. function:: is_tracked(obj) |
| 190 |
|
| 191 |
Returns ``True`` if the object is currently tracked by the garbage collector, |
| 192 |
``False`` otherwise. As a general rule, instances of atomic types aren't |
| 193 |
tracked and instances of non-atomic types (containers, user-defined |
| 194 |
objects...) are. However, some type-specific optimizations can be present |
| 195 |
in order to suppress the garbage collector footprint of simple instances |
| 196 |
(e.g. dicts containing only atomic keys and values):: |
| 197 |
|
| 198 |
>>> gc.is_tracked(0) |
| 199 |
False |
| 200 |
>>> gc.is_tracked("a") |
| 201 |
False |
| 202 |
>>> gc.is_tracked([]) |
| 203 |
True |
| 204 |
>>> gc.is_tracked({}) |
| 205 |
False |
| 206 |
>>> gc.is_tracked({"a": 1}) |
| 207 |
True |
| 208 |
|
| 209 |
.. versionadded:: 3.1 |
| 210 |
|
| 211 |
|
| 212 |
.. function:: is_finalized(obj) |
| 213 |
|
| 214 |
Returns ``True`` if the given object has been finalized by the |
| 215 |
garbage collector, ``False`` otherwise. :: |
| 216 |
|
| 217 |
>>> x = None |
| 218 |
>>> class Lazarus: |
| 219 |
... def __del__(self): |
| 220 |
... global x |
| 221 |
... x = self |
| 222 |
... |
| 223 |
>>> lazarus = Lazarus() |
| 224 |
>>> gc.is_finalized(lazarus) |
| 225 |
False |
| 226 |
>>> del lazarus |
| 227 |
>>> gc.is_finalized(x) |
| 228 |
True |
| 229 |
|
| 230 |
.. versionadded:: 3.9 |
| 231 |
|
| 232 |
|
| 233 |
.. function:: freeze() |
| 234 |
|
| 235 |
Freeze all the objects tracked by the garbage collector; move them to a |
| 236 |
permanent generation and ignore them in all the future collections. |
| 237 |
|
| 238 |
If a process will ``fork()`` without ``exec()``, avoiding unnecessary |
| 239 |
copy-on-write in child processes will maximize memory sharing and reduce |
| 240 |
overall memory usage. This requires both avoiding creation of freed "holes" |
| 241 |
in memory pages in the parent process and ensuring that GC collections in |
| 242 |
child processes won't touch the ``gc_refs`` counter of long-lived objects |
| 243 |
originating in the parent process. To accomplish both, call ``gc.disable()`` |
| 244 |
early in the parent process, ``gc.freeze()`` right before ``fork()``, and |
| 245 |
``gc.enable()`` early in child processes. |
| 246 |
|
| 247 |
.. versionadded:: 3.7 |
| 248 |
|
| 249 |
|
| 250 |
.. function:: unfreeze() |
| 251 |
|
| 252 |
Unfreeze the objects in the permanent generation, put them back into the |
| 253 |
oldest generation. |
| 254 |
|
| 255 |
.. versionadded:: 3.7 |
| 256 |
|
| 257 |
|
| 258 |
.. function:: get_freeze_count() |
| 259 |
|
| 260 |
Return the number of objects in the permanent generation. |
| 261 |
|
| 262 |
.. versionadded:: 3.7 |
| 263 |
|
| 264 |
|
| 265 |
The following variables are provided for read-only access (you can mutate the |
| 266 |
values but should not rebind them): |
| 267 |
|
| 268 |
.. data:: garbage |
| 269 |
|
| 270 |
A list of objects which the collector found to be unreachable but could |
| 271 |
not be freed (uncollectable objects). Starting with Python 3.4, this |
| 272 |
list should be empty most of the time, except when using instances of |
| 273 |
C extension types with a non-``NULL`` ``tp_del`` slot. |
| 274 |
|
| 275 |
If :const:`DEBUG_SAVEALL` is set, then all unreachable objects will be |
| 276 |
added to this list rather than freed. |
| 277 |
|
| 278 |
.. versionchanged:: 3.2 |
| 279 |
If this list is non-empty at :term:`interpreter shutdown`, a |
| 280 |
:exc:`ResourceWarning` is emitted, which is silent by default. If |
| 281 |
:const:`DEBUG_UNCOLLECTABLE` is set, in addition all uncollectable objects |
| 282 |
are printed. |
| 283 |
|
| 284 |
.. versionchanged:: 3.4 |
| 285 |
Following :pep:`442`, objects with a :meth:`~object.__del__` method don't end |
| 286 |
up in :data:`gc.garbage` anymore. |
| 287 |
|
| 288 |
.. data:: callbacks |
| 289 |
|
| 290 |
A list of callbacks that will be invoked by the garbage collector before and |
| 291 |
after collection. The callbacks will be called with two arguments, |
| 292 |
*phase* and *info*. |
| 293 |
|
| 294 |
*phase* can be one of two values: |
| 295 |
|
| 296 |
"start": The garbage collection is about to start. |
| 297 |
|
| 298 |
"stop": The garbage collection has finished. |
| 299 |
|
| 300 |
*info* is a dict providing more information for the callback. The following |
| 301 |
keys are currently defined: |
| 302 |
|
| 303 |
"generation": The oldest generation being collected. |
| 304 |
|
| 305 |
"collected": When *phase* is "stop", the number of objects |
| 306 |
successfully collected. |
| 307 |
|
| 308 |
"uncollectable": When *phase* is "stop", the number of objects |
| 309 |
that could not be collected and were put in :data:`garbage`. |
| 310 |
|
| 311 |
Applications can add their own callbacks to this list. The primary |
| 312 |
use cases are: |
| 313 |
|
| 314 |
Gathering statistics about garbage collection, such as how often |
| 315 |
various generations are collected, and how long the collection |
| 316 |
takes. |
| 317 |
|
| 318 |
Allowing applications to identify and clear their own uncollectable |
| 319 |
types when they appear in :data:`garbage`. |
| 320 |
|
| 321 |
.. versionadded:: 3.3 |
| 322 |
|
| 323 |
|
| 324 |
The following constants are provided for use with :func:`set_debug`: |
| 325 |
|
| 326 |
|
| 327 |
.. data:: DEBUG_STATS |
| 328 |
|
| 329 |
Print statistics during collection. This information can be useful when tuning |
| 330 |
the collection frequency. |
| 331 |
|
| 332 |
|
| 333 |
.. data:: DEBUG_COLLECTABLE |
| 334 |
|
| 335 |
Print information on collectable objects found. |
| 336 |
|
| 337 |
|
| 338 |
.. data:: DEBUG_UNCOLLECTABLE |
| 339 |
|
| 340 |
Print information of uncollectable objects found (objects which are not |
| 341 |
reachable but cannot be freed by the collector). These objects will be added |
| 342 |
to the ``garbage`` list. |
| 343 |
|
| 344 |
.. versionchanged:: 3.2 |
| 345 |
Also print the contents of the :data:`garbage` list at |
| 346 |
:term:`interpreter shutdown`, if it isn't empty. |
| 347 |
|
| 348 |
.. data:: DEBUG_SAVEALL |
| 349 |
|
| 350 |
When set, all unreachable objects found will be appended to *garbage* rather |
| 351 |
than being freed. This can be useful for debugging a leaking program. |
| 352 |
|
| 353 |
|
| 354 |
.. data:: DEBUG_LEAK |
| 355 |
|
| 356 |
The debugging flags necessary for the collector to print information about a |
| 357 |
leaking program (equal to ``DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | |
| 358 |
DEBUG_SAVEALL``). |