gc — 垃圾收集器接口


此模块提供到可选垃圾收集器的接口。它提供禁用收集器、微调收集频率及设置调试选项的能力。它还提供对收集器能发现却无法释放的无法企及对象的访问。由于收集器会增补 Python 已使用的引用计数,因此若确信程序不会创建引用循环,则可以禁用收集器。自动收集可以被禁用通过调用 gc.disable() 。要调试泄漏程序调用 gc.set_debug(gc.DEBUG_LEAK) 。预告,这包括 gc.DEBUG_SAVEALL ,导致垃圾收集对象被保存在 gc.garbage 中以供审查。

gc 模块提供下列函数:

gc. enable ( )

启用自动垃圾收集。

gc. disable ( )

禁用自动垃圾收集。

gc. isenabled ( )

返回 True 如果自动收集被启用。

gc. collect ( generation = 2 )

没有自变量,运行完整收集。可选自变量 generation 可以是指定要收集哪一代 (从 0 到 2) 的整数。 ValueError 被引发若世代数无效。返回找到的无法企及对象数。

由许多内置类型维护的释放列表会被清零,每当运行完整收集或最高 2 世代的收集时。某些释放列表中的所有项可能不会被释放,由于特定实现原因,尤其是 float .

gc. set_debug ( flags )

设置垃圾收集调试标志。调试信息会被写入到 sys.stderr . See below for a list of debugging flags which can be combined using bit operations to control debugging.

gc. get_debug ( )

返回目前设置的调试标志。

gc. get_objects ( generation = None )

Returns a list of all objects tracked by the collector, excluding the list returned. If generation is not None, return only the objects tracked by the collector that are in that generation.

3.8 版改变: New generation 参数。

引发 审计事件 gc.get_objects 采用自变量 generation .

gc. get_stats ( )

Return a list of three per-generation dictionaries containing collection statistics since interpreter start. The number of keys may change in the future, but currently each dictionary will contain the following items:

  • collections is the number of times this generation was collected;

  • collected is the total number of objects collected inside this generation;

  • uncollectable is the total number of objects which were found to be uncollectable (and were therefore moved to the garbage list) inside this generation.

3.4 版新增。

gc. set_threshold ( threshold0 [ , threshold1 [ , threshold2 ] ] )

设置垃圾收集阈值 (收集频率)。设置 threshold0 为 0 禁用收集。

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. With the third generation, things are a bit more complicated, see Collecting the oldest generation 了解更多信息。

gc. get_count ( )

返回当前收集计数按元组 (count0, count1, count2) .

gc. get_threshold ( )

返回当前收集阈值按元组 (threshold0, threshold1, threshold2) .

gc. get_referrers ( * objs )

Return the list of objects that directly refer to any of objs. This function will only locate those containers which support garbage collection; extension types which do refer to other objects but do not support garbage collection will not be found.

Note that objects which have already been dereferenced, but which live in cycles and have not yet been collected by the garbage collector can be listed among the resulting referrers. To get only currently live objects, call collect() before calling get_referrers() .

警告

Care must be taken when using objects returned by get_referrers() because some of them could still be under construction and hence in a temporarily invalid state. Avoid using get_referrers() for any purpose other than debugging.

引发 审计事件 gc.get_referrers 采用自变量 objs .

gc. get_referents ( * objs )

Return a list of objects directly referred to by any of the arguments. The referents returned are those objects visited by the arguments’ C-level tp_traverse methods (if any), and may not be all objects actually directly reachable. tp_traverse methods are supported only by objects that support garbage collection, and are only required to visit objects that may be involved in a cycle. So, for example, if an integer is directly reachable from an argument, that integer object may or may not appear in the result list.

引发 审计事件 gc.get_referents 采用自变量 objs .

gc. is_tracked ( obj )

返回 True if the object is currently tracked by the garbage collector, False otherwise. As a general rule, instances of atomic types aren’t tracked and instances of non-atomic types (containers, user-defined objects…) are. However, some type-specific optimizations can be present in order to suppress the garbage collector footprint of simple instances (e.g. dicts containing only atomic keys and values):

>>> gc.is_tracked(0)
False
>>> gc.is_tracked("a")
False
>>> gc.is_tracked([])
True
>>> gc.is_tracked({})
False
>>> gc.is_tracked({"a": 1})
False
>>> gc.is_tracked({"a": []})
True
						

3.1 版新增。

gc. is_finalized ( obj )

返回 True if the given object has been finalized by the garbage collector, False 否则。

>>> x = None
>>> class Lazarus:
...     def __del__(self):
...         global x
...         x = self
...
>>> lazarus = Lazarus()
>>> gc.is_finalized(lazarus)
False
>>> del lazarus
>>> gc.is_finalized(x)
True
						

3.9 版新增。

gc. freeze ( )

Freeze all the objects tracked by gc - move them to a permanent generation and ignore all the future collections. This can be used before a POSIX fork() call to make the gc copy-on-write friendly or to speed up collection. Also collection before a POSIX fork() call may free pages for future allocation which can cause copy-on-write too so it’s advised to disable gc in parent process and freeze before fork and enable gc in child process.

3.7 版新增。

gc. unfreeze ( )

Unfreeze the objects in the permanent generation, put them back into the oldest generation.

3.7 版新增。

gc. get_freeze_count ( )

Return the number of objects in the permanent generation.

3.7 版新增。

The following variables are provided for read-only access (you can mutate the values but should not rebind them):

gc. garbage

A list of objects which the collector found to be unreachable but could not be freed (uncollectable objects). Starting with Python 3.4, this list should be empty most of the time, except when using instances of C extension types with a non- NULL tp_del 槽。

DEBUG_SAVEALL is set, then all unreachable objects will be added to this list rather than freed.

3.2 版改变: 若此列表非空当 解释器关闭 ResourceWarning is emitted, which is silent by default. If DEBUG_UNCOLLECTABLE is set, in addition all uncollectable objects are printed.

3.4 版改变: 遵循 PEP 442 ,对象具有 __del__() method don’t end up in gc.garbage 不再。

gc. callbacks

A list of callbacks that will be invoked by the garbage collector before and after collection. The callbacks will be called with two arguments, phase and info .

phase can be one of two values:

“start”: The garbage collection is about to start.

“stop”: The garbage collection has finished.

info is a dict providing more information for the callback. The following keys are currently defined:

“generation”: The oldest generation being collected.

“collected”: When phase is “stop”, the number of objects successfully collected.

“uncollectable”: When phase is “stop”, the number of objects that could not be collected and were put in garbage .

Applications can add their own callbacks to this list. The primary use cases are:

Gathering statistics about garbage collection, such as how often various generations are collected, and how long the collection takes.

Allowing applications to identify and clear their own uncollectable types when they appear in garbage .

3.3 版新增。

The following constants are provided for use with set_debug() :

gc. DEBUG_STATS

Print statistics during collection. This information can be useful when tuning the collection frequency.

gc. DEBUG_COLLECTABLE

Print information on collectable objects found.

gc. DEBUG_UNCOLLECTABLE

Print information of uncollectable objects found (objects which are not reachable but cannot be freed by the collector). These objects will be added to the garbage 列表。

3.2 版改变: Also print the contents of the garbage list at 解释器关闭 , if it isn’t empty.

gc. DEBUG_SAVEALL

When set, all unreachable objects found will be appended to garbage rather than being freed. This can be useful for debugging a leaking program.

gc. DEBUG_LEAK

The debugging flags necessary for the collector to print information about a leaking program (equal to DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | DEBUG_SAVEALL ).

上一话题

__future__ — 未来的语句定义

下一话题

inspect — 审查存活对象

本页