gc Module in Python

gc Python Module is a Garbage Collector Interface which provides many functions for dealing with underlying Memory Management/Garbage Collection in Python.

In this article, I’ll discuss about different functions in Python’s gc Module.

gc.enable()Enables Automatic Garbage Collection
gc.disable()Disable Automatic Garbage Collection
gc.isenabled()Returns True if automatic garbage collection is enabled
gc.collect(genearation = 2)Runs a Full Garbage Collection
gc.set_debug(flags)Sets garbage collection debugging flags
gc.get_debug()Returns debugging flags currently set
gc.get_objects(generation=None)Return a lost of all objects tracked by collector
gc.get_stats()Return a list of collection statistics
gc.set_threshold()Set garbage collection thresholds like Collection Frequency
gc.get_count()Return current collection counts as (count0, count1, count2)
gc.get_threshold()Return current collection threshold as (threshold0, threshold1, threshold2)
gc.get_referrers(*objs)Return list of objects that directly refer to any of objs
gc.get_referents(*objs)Return a list of objects directly referred to by any of arguments
gc.is_tracked(obj)Returns True if object is currently tracked by garbage collector, False otherwise
gc.is_finalized(obj)Returns True if given object has been finalized by garbage collector, False otherwise
gc.freeze()Freeze all of objects which are being tracked by Garbage Collector(gc)
gc.unfreeze()Unfreeze objects in permanent generation, but them back into oldest generation
gc.get_freeze_count()Returns number of objects in permanent generation
gc.garbageA list of objects which collector found to be unreachable but could not be freed
gc.callbacksA list of callbacks that will be invoked before or after garbage collection
gc.DEBUG_STATSPrint out statistics during collection
gc.DEBUG_COLLECTABLEPrint out information on collectable objects found
gc.DEBUG_UNCOLLECTABLEPrint out information of uncollectable objects
gc.DEBUG_SAVEALLWhen set, all unreachable objects found will be appended to garbage rather than being freed
gc.DEBUG_LEAKThe debugging flags necessary for collector to print information about a leaking program

Leave a Comment