xref: /third_party/python/Doc/library/gc.rst (revision 7db96d56)
17db96d56Sopenharmony_ci:mod:`gc` --- Garbage Collector interface
27db96d56Sopenharmony_ci=========================================
37db96d56Sopenharmony_ci
47db96d56Sopenharmony_ci.. module:: gc
57db96d56Sopenharmony_ci   :synopsis: Interface to the cycle-detecting garbage collector.
67db96d56Sopenharmony_ci
77db96d56Sopenharmony_ci.. moduleauthor:: Neil Schemenauer <nas@arctrix.com>
87db96d56Sopenharmony_ci.. sectionauthor:: Neil Schemenauer <nas@arctrix.com>
97db96d56Sopenharmony_ci
107db96d56Sopenharmony_ci--------------
117db96d56Sopenharmony_ci
127db96d56Sopenharmony_ciThis module provides an interface to the optional garbage collector.  It
137db96d56Sopenharmony_ciprovides the ability to disable the collector, tune the collection frequency,
147db96d56Sopenharmony_ciand set debugging options.  It also provides access to unreachable objects that
157db96d56Sopenharmony_cithe collector found but cannot free.  Since the collector supplements the
167db96d56Sopenharmony_cireference counting already used in Python, you can disable the collector if you
177db96d56Sopenharmony_ciare sure your program does not create reference cycles.  Automatic collection
187db96d56Sopenharmony_cican be disabled by calling ``gc.disable()``.  To debug a leaking program call
197db96d56Sopenharmony_ci``gc.set_debug(gc.DEBUG_LEAK)``. Notice that this includes
207db96d56Sopenharmony_ci``gc.DEBUG_SAVEALL``, causing garbage-collected objects to be saved in
217db96d56Sopenharmony_cigc.garbage for inspection.
227db96d56Sopenharmony_ci
237db96d56Sopenharmony_ciThe :mod:`gc` module provides the following functions:
247db96d56Sopenharmony_ci
257db96d56Sopenharmony_ci
267db96d56Sopenharmony_ci.. function:: enable()
277db96d56Sopenharmony_ci
287db96d56Sopenharmony_ci   Enable automatic garbage collection.
297db96d56Sopenharmony_ci
307db96d56Sopenharmony_ci
317db96d56Sopenharmony_ci.. function:: disable()
327db96d56Sopenharmony_ci
337db96d56Sopenharmony_ci   Disable automatic garbage collection.
347db96d56Sopenharmony_ci
357db96d56Sopenharmony_ci
367db96d56Sopenharmony_ci.. function:: isenabled()
377db96d56Sopenharmony_ci
387db96d56Sopenharmony_ci   Return ``True`` if automatic collection is enabled.
397db96d56Sopenharmony_ci
407db96d56Sopenharmony_ci
417db96d56Sopenharmony_ci.. function:: collect(generation=2)
427db96d56Sopenharmony_ci
437db96d56Sopenharmony_ci   With no arguments, run a full collection.  The optional argument *generation*
447db96d56Sopenharmony_ci   may be an integer specifying which generation to collect (from 0 to 2).  A
457db96d56Sopenharmony_ci   :exc:`ValueError` is raised if the generation number  is invalid. The number of
467db96d56Sopenharmony_ci   unreachable objects found is returned.
477db96d56Sopenharmony_ci
487db96d56Sopenharmony_ci   The free lists maintained for a number of built-in types are cleared
497db96d56Sopenharmony_ci   whenever a full collection or collection of the highest generation (2)
507db96d56Sopenharmony_ci   is run.  Not all items in some free lists may be freed due to the
517db96d56Sopenharmony_ci   particular implementation, in particular :class:`float`.
527db96d56Sopenharmony_ci
537db96d56Sopenharmony_ci   The effect of calling ``gc.collect()`` while the interpreter is already
547db96d56Sopenharmony_ci   performing a collection is undefined.
557db96d56Sopenharmony_ci
567db96d56Sopenharmony_ci
577db96d56Sopenharmony_ci.. function:: set_debug(flags)
587db96d56Sopenharmony_ci
597db96d56Sopenharmony_ci   Set the garbage collection debugging flags. Debugging information will be
607db96d56Sopenharmony_ci   written to ``sys.stderr``.  See below for a list of debugging flags which can be
617db96d56Sopenharmony_ci   combined using bit operations to control debugging.
627db96d56Sopenharmony_ci
637db96d56Sopenharmony_ci
647db96d56Sopenharmony_ci.. function:: get_debug()
657db96d56Sopenharmony_ci
667db96d56Sopenharmony_ci   Return the debugging flags currently set.
677db96d56Sopenharmony_ci
687db96d56Sopenharmony_ci
697db96d56Sopenharmony_ci.. function:: get_objects(generation=None)
707db96d56Sopenharmony_ci
717db96d56Sopenharmony_ci   Returns a list of all objects tracked by the collector, excluding the list
727db96d56Sopenharmony_ci   returned. If *generation* is not None, return only the objects tracked by
737db96d56Sopenharmony_ci   the collector that are in that generation.
747db96d56Sopenharmony_ci
757db96d56Sopenharmony_ci   .. versionchanged:: 3.8
767db96d56Sopenharmony_ci      New *generation* parameter.
777db96d56Sopenharmony_ci
787db96d56Sopenharmony_ci   .. audit-event:: gc.get_objects generation gc.get_objects
797db96d56Sopenharmony_ci
807db96d56Sopenharmony_ci.. function:: get_stats()
817db96d56Sopenharmony_ci
827db96d56Sopenharmony_ci   Return a list of three per-generation dictionaries containing collection
837db96d56Sopenharmony_ci   statistics since interpreter start.  The number of keys may change
847db96d56Sopenharmony_ci   in the future, but currently each dictionary will contain the following
857db96d56Sopenharmony_ci   items:
867db96d56Sopenharmony_ci
877db96d56Sopenharmony_ci   * ``collections`` is the number of times this generation was collected;
887db96d56Sopenharmony_ci
897db96d56Sopenharmony_ci   * ``collected`` is the total number of objects collected inside this
907db96d56Sopenharmony_ci     generation;
917db96d56Sopenharmony_ci
927db96d56Sopenharmony_ci   * ``uncollectable`` is the total number of objects which were found
937db96d56Sopenharmony_ci     to be uncollectable (and were therefore moved to the :data:`garbage`
947db96d56Sopenharmony_ci     list) inside this generation.
957db96d56Sopenharmony_ci
967db96d56Sopenharmony_ci   .. versionadded:: 3.4
977db96d56Sopenharmony_ci
987db96d56Sopenharmony_ci
997db96d56Sopenharmony_ci.. function:: set_threshold(threshold0[, threshold1[, threshold2]])
1007db96d56Sopenharmony_ci
1017db96d56Sopenharmony_ci   Set the garbage collection thresholds (the collection frequency). Setting
1027db96d56Sopenharmony_ci   *threshold0* to zero disables collection.
1037db96d56Sopenharmony_ci
1047db96d56Sopenharmony_ci   The GC classifies objects into three generations depending on how many
1057db96d56Sopenharmony_ci   collection sweeps they have survived.  New objects are placed in the youngest
1067db96d56Sopenharmony_ci   generation (generation ``0``).  If an object survives a collection it is moved
1077db96d56Sopenharmony_ci   into the next older generation.  Since generation ``2`` is the oldest
1087db96d56Sopenharmony_ci   generation, objects in that generation remain there after a collection.  In
1097db96d56Sopenharmony_ci   order to decide when to run, the collector keeps track of the number object
1107db96d56Sopenharmony_ci   allocations and deallocations since the last collection.  When the number of
1117db96d56Sopenharmony_ci   allocations minus the number of deallocations exceeds *threshold0*, collection
1127db96d56Sopenharmony_ci   starts.  Initially only generation ``0`` is examined.  If generation ``0`` has
1137db96d56Sopenharmony_ci   been examined more than *threshold1* times since generation ``1`` has been
1147db96d56Sopenharmony_ci   examined, then generation ``1`` is examined as well.
1157db96d56Sopenharmony_ci   With the third generation, things are a bit more complicated,
1167db96d56Sopenharmony_ci   see `Collecting the oldest generation <https://devguide.python.org/garbage_collector/#collecting-the-oldest-generation>`_ for more information.
1177db96d56Sopenharmony_ci
1187db96d56Sopenharmony_ci
1197db96d56Sopenharmony_ci.. function:: get_count()
1207db96d56Sopenharmony_ci
1217db96d56Sopenharmony_ci   Return the current collection  counts as a tuple of ``(count0, count1,
1227db96d56Sopenharmony_ci   count2)``.
1237db96d56Sopenharmony_ci
1247db96d56Sopenharmony_ci
1257db96d56Sopenharmony_ci.. function:: get_threshold()
1267db96d56Sopenharmony_ci
1277db96d56Sopenharmony_ci   Return the current collection thresholds as a tuple of ``(threshold0,
1287db96d56Sopenharmony_ci   threshold1, threshold2)``.
1297db96d56Sopenharmony_ci
1307db96d56Sopenharmony_ci
1317db96d56Sopenharmony_ci.. function:: get_referrers(*objs)
1327db96d56Sopenharmony_ci
1337db96d56Sopenharmony_ci   Return the list of objects that directly refer to any of objs. This function
1347db96d56Sopenharmony_ci   will only locate those containers which support garbage collection; extension
1357db96d56Sopenharmony_ci   types which do refer to other objects but do not support garbage collection will
1367db96d56Sopenharmony_ci   not be found.
1377db96d56Sopenharmony_ci
1387db96d56Sopenharmony_ci   Note that objects which have already been dereferenced, but which live in cycles
1397db96d56Sopenharmony_ci   and have not yet been collected by the garbage collector can be listed among the
1407db96d56Sopenharmony_ci   resulting referrers.  To get only currently live objects, call :func:`collect`
1417db96d56Sopenharmony_ci   before calling :func:`get_referrers`.
1427db96d56Sopenharmony_ci
1437db96d56Sopenharmony_ci   .. warning::
1447db96d56Sopenharmony_ci      Care must be taken when using objects returned by :func:`get_referrers` because
1457db96d56Sopenharmony_ci      some of them could still be under construction and hence in a temporarily
1467db96d56Sopenharmony_ci      invalid state. Avoid using :func:`get_referrers` for any purpose other than
1477db96d56Sopenharmony_ci      debugging.
1487db96d56Sopenharmony_ci
1497db96d56Sopenharmony_ci   .. audit-event:: gc.get_referrers objs gc.get_referrers
1507db96d56Sopenharmony_ci
1517db96d56Sopenharmony_ci
1527db96d56Sopenharmony_ci.. function:: get_referents(*objs)
1537db96d56Sopenharmony_ci
1547db96d56Sopenharmony_ci   Return a list of objects directly referred to by any of the arguments. The
1557db96d56Sopenharmony_ci   referents returned are those objects visited by the arguments' C-level
1567db96d56Sopenharmony_ci   :c:member:`~PyTypeObject.tp_traverse` methods (if any), and may not be all objects actually
1577db96d56Sopenharmony_ci   directly reachable.  :c:member:`~PyTypeObject.tp_traverse` methods are supported only by objects
1587db96d56Sopenharmony_ci   that support garbage collection, and are only required to visit objects that may
1597db96d56Sopenharmony_ci   be involved in a cycle.  So, for example, if an integer is directly reachable
1607db96d56Sopenharmony_ci   from an argument, that integer object may or may not appear in the result list.
1617db96d56Sopenharmony_ci
1627db96d56Sopenharmony_ci   .. audit-event:: gc.get_referents objs gc.get_referents
1637db96d56Sopenharmony_ci
1647db96d56Sopenharmony_ci.. function:: is_tracked(obj)
1657db96d56Sopenharmony_ci
1667db96d56Sopenharmony_ci   Returns ``True`` if the object is currently tracked by the garbage collector,
1677db96d56Sopenharmony_ci   ``False`` otherwise.  As a general rule, instances of atomic types aren't
1687db96d56Sopenharmony_ci   tracked and instances of non-atomic types (containers, user-defined
1697db96d56Sopenharmony_ci   objects...) are.  However, some type-specific optimizations can be present
1707db96d56Sopenharmony_ci   in order to suppress the garbage collector footprint of simple instances
1717db96d56Sopenharmony_ci   (e.g. dicts containing only atomic keys and values)::
1727db96d56Sopenharmony_ci
1737db96d56Sopenharmony_ci      >>> gc.is_tracked(0)
1747db96d56Sopenharmony_ci      False
1757db96d56Sopenharmony_ci      >>> gc.is_tracked("a")
1767db96d56Sopenharmony_ci      False
1777db96d56Sopenharmony_ci      >>> gc.is_tracked([])
1787db96d56Sopenharmony_ci      True
1797db96d56Sopenharmony_ci      >>> gc.is_tracked({})
1807db96d56Sopenharmony_ci      False
1817db96d56Sopenharmony_ci      >>> gc.is_tracked({"a": 1})
1827db96d56Sopenharmony_ci      False
1837db96d56Sopenharmony_ci      >>> gc.is_tracked({"a": []})
1847db96d56Sopenharmony_ci      True
1857db96d56Sopenharmony_ci
1867db96d56Sopenharmony_ci   .. versionadded:: 3.1
1877db96d56Sopenharmony_ci
1887db96d56Sopenharmony_ci
1897db96d56Sopenharmony_ci.. function:: is_finalized(obj)
1907db96d56Sopenharmony_ci
1917db96d56Sopenharmony_ci   Returns ``True`` if the given object has been finalized by the
1927db96d56Sopenharmony_ci   garbage collector, ``False`` otherwise. ::
1937db96d56Sopenharmony_ci
1947db96d56Sopenharmony_ci      >>> x = None
1957db96d56Sopenharmony_ci      >>> class Lazarus:
1967db96d56Sopenharmony_ci      ...     def __del__(self):
1977db96d56Sopenharmony_ci      ...         global x
1987db96d56Sopenharmony_ci      ...         x = self
1997db96d56Sopenharmony_ci      ...
2007db96d56Sopenharmony_ci      >>> lazarus = Lazarus()
2017db96d56Sopenharmony_ci      >>> gc.is_finalized(lazarus)
2027db96d56Sopenharmony_ci      False
2037db96d56Sopenharmony_ci      >>> del lazarus
2047db96d56Sopenharmony_ci      >>> gc.is_finalized(x)
2057db96d56Sopenharmony_ci      True
2067db96d56Sopenharmony_ci
2077db96d56Sopenharmony_ci   .. versionadded:: 3.9
2087db96d56Sopenharmony_ci
2097db96d56Sopenharmony_ci
2107db96d56Sopenharmony_ci.. function:: freeze()
2117db96d56Sopenharmony_ci
2127db96d56Sopenharmony_ci   Freeze all the objects tracked by the garbage collector; move them to a
2137db96d56Sopenharmony_ci   permanent generation and ignore them in all the future collections.
2147db96d56Sopenharmony_ci
2157db96d56Sopenharmony_ci   If a process will ``fork()`` without ``exec()``, avoiding unnecessary
2167db96d56Sopenharmony_ci   copy-on-write in child processes will maximize memory sharing and reduce
2177db96d56Sopenharmony_ci   overall memory usage. This requires both avoiding creation of freed "holes"
2187db96d56Sopenharmony_ci   in memory pages in the parent process and ensuring that GC collections in
2197db96d56Sopenharmony_ci   child processes won't touch the ``gc_refs`` counter of long-lived objects
2207db96d56Sopenharmony_ci   originating in the parent process. To accomplish both, call ``gc.disable()``
2217db96d56Sopenharmony_ci   early in the parent process, ``gc.freeze()`` right before ``fork()``, and
2227db96d56Sopenharmony_ci   ``gc.enable()`` early in child processes.
2237db96d56Sopenharmony_ci
2247db96d56Sopenharmony_ci   .. versionadded:: 3.7
2257db96d56Sopenharmony_ci
2267db96d56Sopenharmony_ci
2277db96d56Sopenharmony_ci.. function:: unfreeze()
2287db96d56Sopenharmony_ci
2297db96d56Sopenharmony_ci   Unfreeze the objects in the permanent generation, put them back into the
2307db96d56Sopenharmony_ci   oldest generation.
2317db96d56Sopenharmony_ci
2327db96d56Sopenharmony_ci   .. versionadded:: 3.7
2337db96d56Sopenharmony_ci
2347db96d56Sopenharmony_ci
2357db96d56Sopenharmony_ci.. function:: get_freeze_count()
2367db96d56Sopenharmony_ci
2377db96d56Sopenharmony_ci   Return the number of objects in the permanent generation.
2387db96d56Sopenharmony_ci
2397db96d56Sopenharmony_ci   .. versionadded:: 3.7
2407db96d56Sopenharmony_ci
2417db96d56Sopenharmony_ci
2427db96d56Sopenharmony_ciThe following variables are provided for read-only access (you can mutate the
2437db96d56Sopenharmony_civalues but should not rebind them):
2447db96d56Sopenharmony_ci
2457db96d56Sopenharmony_ci.. data:: garbage
2467db96d56Sopenharmony_ci
2477db96d56Sopenharmony_ci   A list of objects which the collector found to be unreachable but could
2487db96d56Sopenharmony_ci   not be freed (uncollectable objects).  Starting with Python 3.4, this
2497db96d56Sopenharmony_ci   list should be empty most of the time, except when using instances of
2507db96d56Sopenharmony_ci   C extension types with a non-``NULL`` ``tp_del`` slot.
2517db96d56Sopenharmony_ci
2527db96d56Sopenharmony_ci   If :const:`DEBUG_SAVEALL` is set, then all unreachable objects will be
2537db96d56Sopenharmony_ci   added to this list rather than freed.
2547db96d56Sopenharmony_ci
2557db96d56Sopenharmony_ci   .. versionchanged:: 3.2
2567db96d56Sopenharmony_ci      If this list is non-empty at :term:`interpreter shutdown`, a
2577db96d56Sopenharmony_ci      :exc:`ResourceWarning` is emitted, which is silent by default.  If
2587db96d56Sopenharmony_ci      :const:`DEBUG_UNCOLLECTABLE` is set, in addition all uncollectable objects
2597db96d56Sopenharmony_ci      are printed.
2607db96d56Sopenharmony_ci
2617db96d56Sopenharmony_ci   .. versionchanged:: 3.4
2627db96d56Sopenharmony_ci      Following :pep:`442`, objects with a :meth:`__del__` method don't end
2637db96d56Sopenharmony_ci      up in :attr:`gc.garbage` anymore.
2647db96d56Sopenharmony_ci
2657db96d56Sopenharmony_ci.. data:: callbacks
2667db96d56Sopenharmony_ci
2677db96d56Sopenharmony_ci   A list of callbacks that will be invoked by the garbage collector before and
2687db96d56Sopenharmony_ci   after collection.  The callbacks will be called with two arguments,
2697db96d56Sopenharmony_ci   *phase* and *info*.
2707db96d56Sopenharmony_ci
2717db96d56Sopenharmony_ci   *phase* can be one of two values:
2727db96d56Sopenharmony_ci
2737db96d56Sopenharmony_ci      "start": The garbage collection is about to start.
2747db96d56Sopenharmony_ci
2757db96d56Sopenharmony_ci      "stop": The garbage collection has finished.
2767db96d56Sopenharmony_ci
2777db96d56Sopenharmony_ci   *info* is a dict providing more information for the callback.  The following
2787db96d56Sopenharmony_ci   keys are currently defined:
2797db96d56Sopenharmony_ci
2807db96d56Sopenharmony_ci      "generation": The oldest generation being collected.
2817db96d56Sopenharmony_ci
2827db96d56Sopenharmony_ci      "collected": When *phase* is "stop", the number of objects
2837db96d56Sopenharmony_ci      successfully collected.
2847db96d56Sopenharmony_ci
2857db96d56Sopenharmony_ci      "uncollectable": When *phase* is "stop", the number of objects
2867db96d56Sopenharmony_ci      that could not be collected and were put in :data:`garbage`.
2877db96d56Sopenharmony_ci
2887db96d56Sopenharmony_ci   Applications can add their own callbacks to this list.  The primary
2897db96d56Sopenharmony_ci   use cases are:
2907db96d56Sopenharmony_ci
2917db96d56Sopenharmony_ci      Gathering statistics about garbage collection, such as how often
2927db96d56Sopenharmony_ci      various generations are collected, and how long the collection
2937db96d56Sopenharmony_ci      takes.
2947db96d56Sopenharmony_ci
2957db96d56Sopenharmony_ci      Allowing applications to identify and clear their own uncollectable
2967db96d56Sopenharmony_ci      types when they appear in :data:`garbage`.
2977db96d56Sopenharmony_ci
2987db96d56Sopenharmony_ci   .. versionadded:: 3.3
2997db96d56Sopenharmony_ci
3007db96d56Sopenharmony_ci
3017db96d56Sopenharmony_ciThe following constants are provided for use with :func:`set_debug`:
3027db96d56Sopenharmony_ci
3037db96d56Sopenharmony_ci
3047db96d56Sopenharmony_ci.. data:: DEBUG_STATS
3057db96d56Sopenharmony_ci
3067db96d56Sopenharmony_ci   Print statistics during collection.  This information can be useful when tuning
3077db96d56Sopenharmony_ci   the collection frequency.
3087db96d56Sopenharmony_ci
3097db96d56Sopenharmony_ci
3107db96d56Sopenharmony_ci.. data:: DEBUG_COLLECTABLE
3117db96d56Sopenharmony_ci
3127db96d56Sopenharmony_ci   Print information on collectable objects found.
3137db96d56Sopenharmony_ci
3147db96d56Sopenharmony_ci
3157db96d56Sopenharmony_ci.. data:: DEBUG_UNCOLLECTABLE
3167db96d56Sopenharmony_ci
3177db96d56Sopenharmony_ci   Print information of uncollectable objects found (objects which are not
3187db96d56Sopenharmony_ci   reachable but cannot be freed by the collector).  These objects will be added
3197db96d56Sopenharmony_ci   to the ``garbage`` list.
3207db96d56Sopenharmony_ci
3217db96d56Sopenharmony_ci   .. versionchanged:: 3.2
3227db96d56Sopenharmony_ci      Also print the contents of the :data:`garbage` list at
3237db96d56Sopenharmony_ci      :term:`interpreter shutdown`, if it isn't empty.
3247db96d56Sopenharmony_ci
3257db96d56Sopenharmony_ci.. data:: DEBUG_SAVEALL
3267db96d56Sopenharmony_ci
3277db96d56Sopenharmony_ci   When set, all unreachable objects found will be appended to *garbage* rather
3287db96d56Sopenharmony_ci   than being freed.  This can be useful for debugging a leaking program.
3297db96d56Sopenharmony_ci
3307db96d56Sopenharmony_ci
3317db96d56Sopenharmony_ci.. data:: DEBUG_LEAK
3327db96d56Sopenharmony_ci
3337db96d56Sopenharmony_ci   The debugging flags necessary for the collector to print information about a
3347db96d56Sopenharmony_ci   leaking program (equal to ``DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE |
3357db96d56Sopenharmony_ci   DEBUG_SAVEALL``).
336