gc — Garbage Collector interface


This module provides an interface to the optional garbage collector. Itprovides the ability to disable the collector, tune the collection frequency,and set debugging options. It also provides access to unreachable objects thatthe collector found but cannot free. Since the collector supplements thereference counting already used in Python, you can disable the collector if youare sure your program does not create reference cycles. Automatic collectioncan be disabled by callinggc.disable(). To debug a leaking program callgc.set_debug(gc.DEBUG_LEAK). Notice that this includesgc.DEBUG_SAVEALL, causing garbage-collected objects to be saved ingc.garbage for inspection.

Thegc module provides the following functions:

gc.enable()

Enable automatic garbage collection.

gc.disable()

Disable automatic garbage collection.

gc.isenabled()

ReturnTrue if automatic collection is enabled.

gc.collect(generation=2)

Perform a collection. The optional argumentgenerationmay be an integer specifying which generation to collect (from 0 to 2). AValueError is raised if the generation number is invalid. The sum ofcollected objects and uncollectable objects is returned.

Callinggc.collect(0) will perform a GC collection on the young generation.

Callinggc.collect(1) will perform a GC collection on the young generationand an increment of the old generation.

Callinggc.collect(2) orgc.collect() performs a full collection

The free lists maintained for a number of built-in types are clearedwhenever a full collection or collection of the highest generation (2)is run. Not all items in some free lists may be freed due to theparticular implementation, in particularfloat.

The effect of callinggc.collect() while the interpreter is alreadyperforming a collection is undefined.

Άλλαξε στην έκδοση 3.13:generation=1 performs an increment of collection.

gc.set_debug(flags)

Set the garbage collection debugging flags. Debugging information will bewritten tosys.stderr. See below for a list of debugging flags which can becombined 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 listreturned. Ifgeneration is notNone, return only the objects as follows:

  • 0: All objects in the young generation

  • 1: No objects, as there is no generation 1 (as of Python 3.13)

  • 2: All objects in the old generation

Άλλαξε στην έκδοση 3.8:Newgeneration parameter.

Άλλαξε στην έκδοση 3.13:Generation 1 is removed

Raises anauditing eventgc.get_objects with argumentgeneration.

gc.get_stats()

Return a list of three per-generation dictionaries containing collectionstatistics since interpreter start. The number of keys may changein the future, but currently each dictionary will contain the followingitems:

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

  • collected is the total number of objects collected inside thisgeneration;

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

Added in version 3.4.

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

Set the garbage collection thresholds (the collection frequency). Settingthreshold0 to zero disables collection.

The GC classifies objects into two generations depending on whether they havesurvived a collection. New objects are placed in the young generation. If anobject survives a collection it is moved into the old generation.

In order to decide when to run, the collector keeps track of the number of objectallocations and deallocations since the last collection. When the number ofallocations minus the number of deallocations exceedsthreshold0, collectionstarts. For each collection, all the objects in the young generation and somefraction of the old generation is collected.

In the free-threaded build, the increase in process memory usage is alsochecked before running the collector. If the memory usage has not increasedby 10% since the last collection and the net number of object allocationshas not exceeded 40 timesthreshold0, the collection is not run.

The fraction of the old generation that is collected isinversely proportionaltothreshold1. The largerthreshold1 is, the slower objects in the old generationare collected.For the default value of 10, 1% of the old generation is scanned during each collection.

threshold2 is ignored.

SeeGarbage collector design for more information.

Άλλαξε στην έκδοση 3.13:threshold2 is ignored

gc.get_count()

Return the current collection counts as a tuple of(count0,count1,count2).

gc.get_threshold()

Return the current collection thresholds as a tuple of(threshold0,threshold1,threshold2).

gc.get_referrers(*objs)

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

Note that objects which have already been dereferenced, but which live in cyclesand have not yet been collected by the garbage collector can be listed among theresulting referrers. To get only currently live objects, callcollect()before callingget_referrers().

Προειδοποίηση

Care must be taken when using objects returned byget_referrers() becausesome of them could still be under construction and hence in a temporarilyinvalid state. Avoid usingget_referrers() for any purpose other thandebugging.

Raises anauditing eventgc.get_referrers with argumentobjs.

gc.get_referents(*objs)

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

Raises anauditing eventgc.get_referents with argumentobjs.

gc.is_tracked(obj)

ReturnsTrue if the object is currently tracked by the garbage collector,False otherwise. As a general rule, instances of atomic types aren’ttracked and instances of non-atomic types (containers, user-definedobjects…) are. However, some type-specific optimizations can be presentin 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})True

Added in version 3.1.

gc.is_finalized(obj)

ReturnsTrue if the given object has been finalized by thegarbage collector,False otherwise.

>>>x=None>>>classLazarus:...def__del__(self):...globalx...x=self...>>>lazarus=Lazarus()>>>gc.is_finalized(lazarus)False>>>dellazarus>>>gc.is_finalized(x)True

Added in version 3.9.

gc.freeze()

Freeze all the objects tracked by the garbage collector; move them to apermanent generation and ignore them in all the future collections.

If a process willfork() withoutexec(), avoiding unnecessarycopy-on-write in child processes will maximize memory sharing and reduceoverall memory usage. This requires both avoiding creation of freed «holes»in memory pages in the parent process and ensuring that GC collections inchild processes won’t touch thegc_refs counter of long-lived objectsoriginating in the parent process. To accomplish both, callgc.disable()early in the parent process,gc.freeze() right beforefork(), andgc.enable() early in child processes.

Added in version 3.7.

gc.unfreeze()

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

Added in version 3.7.

gc.get_freeze_count()

Return the number of objects in the permanent generation.

Added in version 3.7.

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

gc.garbage

A list of objects which the collector found to be unreachable but couldnot be freed (uncollectable objects). Starting with Python 3.4, thislist should be empty most of the time, except when using instances ofC extension types with a non-NULLtp_del slot.

IfDEBUG_SAVEALL is set, then all unreachable objects will beadded to this list rather than freed.

Άλλαξε στην έκδοση 3.2:If this list is non-empty atinterpreter shutdown, aResourceWarning is emitted, which is silent by default. IfDEBUG_UNCOLLECTABLE is set, in addition all uncollectable objectsare printed.

Άλλαξε στην έκδοση 3.4:FollowingPEP 442, objects with a__del__() method don’t endup ingc.garbage anymore.

gc.callbacks

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

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 followingkeys are currently defined:

«generation»: The oldest generation being collected.

«collected»: Whenphase is «stop», the number of objectssuccessfully collected.

«uncollectable»: Whenphase is «stop», the number of objectsthat could not be collected and were put ingarbage.

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

Gathering statistics about garbage collection, such as how oftenvarious generations are collected, and how long the collectiontakes.

Allowing applications to identify and clear their own uncollectabletypes when they appear ingarbage.

Added in version 3.3.

The following constants are provided for use withset_debug():

gc.DEBUG_STATS

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

gc.DEBUG_COLLECTABLE

Print information on collectable objects found.

gc.DEBUG_UNCOLLECTABLE

Print information of uncollectable objects found (objects which are notreachable but cannot be freed by the collector). These objects will be addedto thegarbage list.

Άλλαξε στην έκδοση 3.2:Also print the contents of thegarbage list atinterpreter shutdown, if it isn’t empty.

gc.DEBUG_SAVEALL

When set, all unreachable objects found will be appended togarbage ratherthan 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 aleaking program (equal toDEBUG_COLLECTABLE|DEBUG_UNCOLLECTABLE|DEBUG_SAVEALL).