Python Garbage Collector interface (gc)

PythonServer Side ProgrammingProgramming

Automatic garbage collection is one of the important features of Python. Garbage collector mechanism attempts to reclaim memory occupied by objects that are no longer in use by the program.

Python uses reference counting mechanism for garbage collection. Python interpreter keeps count of number of times an object is referenced by other objects. When references to an object are removed, the count for an object is decremented. When the reference count becomes zero, the object memory is reclaimed.

Normally this mechanism is performed automatically. However, it can be done on purpose if a certain situation arises in the program. The 'gc' module defines the garbage collection interface. Following functions are defined in 'gc' module

 Enable automatic garbage collection.
 Disable automatic garbage collection.
 Returns true if the automatic collection is enabled.
With no arguments, run a full collection. The optional integer argument specifies which generation to collect(from 0 to 2). A ValueError is raised if the generation number is invalid. The number of unreachable objects found is returned.
 Set the garbage collection thresholds (thecollection frequency).
 Return the current collection thresholds as a tuple
 A list of callbacks that will be invoked by the garbage collector before and after collection.
Published on 17-Jan-2019 12:17:25