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