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