What is Garbage Collector in Python and how does it work?
sobes.tech AI
Answer from AI
Garbage Collector (GC) in Python is an automatic memory management mechanism that frees memory occupied by objects that are no longer in use by the program.
Python uses several methods for this:
-
Reference counting: each object maintains a reference count — the number of variables or other objects that refer to it. When the count drops to zero, the object is immediately deleted.
-
Cyclic garbage collector: reference counting cannot free objects involved in cyclic references (when objects refer to each other). For this, Python runs an additional cycle collector that periodically searches for such cycles and deletes them.
Example:
import gc
class A:
def __init__(self):
self.ref = None
# Create a cyclic reference
obj1 = A()
obj2 = A()
obj1.ref = obj2
obj2.ref = obj1
# Remove external references
del obj1
del obj2
# The cyclic collector will free the memory
gc.collect()
Thus, the Garbage Collector helps prevent memory leaks and relieves the programmer from manually managing memory.