gcGarbage Collector interface垃圾收集器接口


This module provides an interface to the optional garbage collector. 此模块提供到可选垃圾收集器的接口。It provides the ability to disable the collector, tune the collection frequency, and set debugging options. 它提供了禁用收集器、调整收集频率和设置调试选项的功能。It also provides access to unreachable objects that the collector found but cannot free. 它还提供对收集器找到但无法释放的不可访问对象的访问。Since the collector supplements the reference counting already used in Python, you can disable the collector if you are sure your program does not create reference cycles. 由于收集器补充了Python中已经使用的引用计数,因此如果您确定您的程序没有创建引用循环,则可以禁用收集器。Automatic collection can be disabled by calling gc.disable(). 可以通过调用gc.disable()禁用自动收集。To debug a leaking program call gc.set_debug(gc.DEBUG_LEAK). 要调试泄漏程序,请调用gc.set_debug(gc.DEBUG_LEAK)Notice that this includes gc.DEBUG_SAVEALL, causing garbage-collected objects to be saved in gc.garbage for inspection.请注意,这包括gc.DEBUG_SAVEALL,导致垃圾收集的对象保存在gc.garbage中以供检查。

The gc module provides the following functions:gc模块提供以下功能:

gc.enable()

Enable automatic garbage collection.启用自动垃圾收集。

gc.disable()

Disable automatic garbage collection.禁用自动垃圾收集。

gc.isenabled()

Return True if automatic collection is enabled.如果启用了自动收集,则返回True

gc.collect(generation=2)

With no arguments, run a full collection. 在没有参数的情况下,运行完整集合。The optional argument generation may be an integer specifying which generation to collect (from 0 to 2). 可选参数generation可以是一个整数,指定要收集的生成(从0到2)。A ValueError is raised if the generation number is invalid. 如果生成号无效,将引发ValueErrorThe number of unreachable objects found is returned.返回找到的不可访问对象数。

The free lists maintained for a number of built-in types are cleared whenever a full collection or collection of the highest generation (2) is run. 每当运行完整集合或最高代集合(2)时,为许多内置类型维护的空闲列表将被清除。Not all items in some free lists may be freed due to the particular implementation, in particular float.由于特定的实现,特别是float,某些自由列表中的所有项都可能被释放。

gc.set_debug(flags)

Set the garbage collection debugging flags. 设置垃圾收集调试标志。Debugging information will be written to sys.stderr. 调试信息将写入sys.stderrSee below for a list of debugging flags which can be combined using bit operations to control debugging.请参阅下面的调试标志列表,可以使用位操作组合这些标志来控制调试。

gc.get_debug()

Return the debugging flags currently set.返回当前设置的调试标志。

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.如果generation不是None,则仅返回收集器在该生成中跟踪的对象。

Changed in version 3.8:版本3.8中更改: New generation parameter.新增的generation参数

Raises an auditing event gc.get_objects with argument generation.引发带有参数generation审核事件gc.get_objects

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.是在这一代中发现无法收集(因此被移动到garbage列表)的对象总数。

New in version 3.4.版本3.4中新增。

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

Set the garbage collection thresholds (the collection frequency). 设置垃圾收集阈值(收集频率)。Setting threshold0 to zero disables collection.threshold0设置为零将禁用收集。

The GC classifies objects into three generations depending on how many collection sweeps they have survived. GC根据对象存活的收集扫描次数将对象分为三代。New objects are placed in the youngest generation (generation 0). 新对象将放置在最年轻的一代(第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. 由于第2代是最老的一代,因此该代中的对象在收集后仍保留在那里。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. 当分配数减去解除分配数超过threshold0时,收集开始。Initially only generation 0 is examined. 最初只检查第0代。If generation 0 has been examined more than threshold1 times since generation 1 has been examined, then generation 1 is examined as well. 如果自检查第1代以来,第0代已检查超过threshold1次,则第1代也将检查。With the third generation, things are a bit more complicated, see Collecting the oldest generation for more information.对于第三代,情况更为复杂,有关更多信息,请参阅收集最老的一代

gc.get_count()

Return the current collection counts as a tuple of (count0, count1, count2).将当前集合计数作为(count0, count1, count2)的元组返回。

gc.get_threshold()

Return the current collection thresholds as a tuple of (threshold0, threshold1, threshold2).将当前收集阈值作为(threshold0, threshold1, threshold2)的元组返回。

gc.get_referrers(*objs)

Return the list of objects that directly refer to any of objs. 返回直接引用任何OBJ的对象列表。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().要仅获取当前活动的对象,请在调用get_referrers()之前调用collect()

Warning警告

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. 使用get_referrers()返回的对象时必须小心,因为其中一些对象可能仍在构造中,因此处于暂时无效状态。Avoid using get_referrers() for any purpose other than debugging.避免将get_referrers()用于调试以外的任何目的。

Raises an auditing event gc.get_referrers with argument objs.使用参数objs引发审核事件gc.get_referers

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. 返回的引用是由参数的C级tp_traverse方法(如果有)访问的对象,并且可能不是所有实际可直接访问的对象。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. tp_traverse方法仅由支持垃圾收集的对象支持,并且仅在访问可能涉及循环的对象时才需要。So, for example, if an integer is directly reachable from an argument, that integer object may or may not appear in the result list.因此,例如,如果可以从参数直接访问整数,则该整数对象可能会或可能不会出现在结果列表中。

Raises an auditing event gc.get_referents with argument objs.使用参数objs引发审核事件gc.get_referents

gc.is_tracked(obj)

Returns True if the object is currently tracked by the garbage collector, False otherwise. 如果垃圾收集器当前正在跟踪对象,则返回True,否则返回FalseAs 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):但是,可以存在一些特定于类型的优化,以抑制简单实例的垃圾收集器占用(例如,仅包含原子键和值的DICT):

>>> 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

New in version 3.1.版本3.1中新增。

gc.is_finalized(obj)

Returns True if the given object has been finalized by the garbage collector, False otherwise.如果给定对象已由垃圾收集器完成,则返回True,否则返回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

New in version 3.9.版本3.9中新增。

gc.freeze()

Freeze all the objects tracked by gc - move them to a permanent generation and ignore all the future collections. 冻结gc跟踪的所有对象-将它们移动到永久生成,并忽略所有未来的集合。This can be used before a POSIX fork() call to make the gc copy-on-write friendly or to speed up collection. 这可以在POSIX fork()调用之前使用,以使gc副本对写友好或加快收集速度。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.此外,POSIX fork()调用之前的收集可能会释放页面供将来分配,这也可能导致写时复制,因此建议在父进程中禁用gc,在fork之前冻结,并在子进程中启用gc。

New in version 3.7.版本3.7中新增。

gc.unfreeze()

Unfreeze the objects in the permanent generation, put them back into the oldest generation.解冻永久生成中的对象,将其放回最老的生成中。

New in version 3.7.版本3.7中新增。

gc.get_freeze_count()

Return the number of objects in the permanent generation.返回永久生成中的对象数。

New in version 3.7.版本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 slot.从Python 3.4开始,该列表在大多数情况下都应该为空,除非使用具有非空tp_del插槽的C扩展类型实例。

If DEBUG_SAVEALL is set, then all unreachable objects will be added to this list rather than freed.如果设置了DEBUG_SAVEALL,则所有无法访问的对象将添加到此列表中,而不是释放。

Changed in version 3.2:版本3.2中更改: If this list is non-empty at interpreter shutdown, a ResourceWarning is emitted, which is silent by default. 如果此列表在解释器关闭时不为空,则会发出ResourceWarning,默认情况下为静默。If DEBUG_UNCOLLECTABLE is set, in addition all uncollectable objects are printed.如果设置了DEBUG_UNCOLLECTABLE,则会打印所有不可收集的对象。

Changed in version 3.4:版本3.4中更改: Following PEP 442, objects with a __del__() method don’t end up in gc.garbage anymore.PEP 442之后,具有__del__()方法的对象不再出现在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.回调将使用两个参数调用,即phaseinfo

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. 是为回调提供更多信息的dict。The following keys are currently defined:当前定义了以下键:

“generation”: The oldest generation being collected.:正在收集的最老一代。

“collected”: When phase is “stop”, the number of objects successfully collected.:当phase为“stop”时,成功收集的对象数。

“uncollectable”: When phase is “stop”, the number of objects that could not be collected and were put in garbage.:当phase为“stop”时,无法收集并放入垃圾的对象数。

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.当它们出现在garbage中时,允许应用程序识别和清除它们自己的不可收集类型。

New in version 3.3.版本3.3中新增。

The following constants are provided for use with set_debug():提供了以下常量用于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 list.这些对象将被添加到garbage列表中。

Changed in version 3.2:版本3.2中更改: Also print the contents of the garbage list at interpreter shutdown, 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.设置后,找到的所有不可访问对象将被附加到garbage中,而不是被释放。这对于调试泄漏程序非常有用。

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).收集器打印有关泄漏程序的信息所需的调试标志(等于DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | DEBUG_SAVEALL)。