Tell me about the Garbage Collector in Python — how does it work?
sobes.tech AI
Answer from AI
Memory management in Python is based on reference counting and an additional garbage collector for cyclic references.
Main points:
-
Reference counting: Each object in Python maintains a reference count — the number of active references to it. When the count drops to zero, the object is immediately deleted and memory is freed.
-
Cyclic references problem: If objects reference each other but are not used, reference counting cannot delete them because their counts are not zero.
-
Garbage collector (GC): To solve the cycle problem, the
gcmodule is used, which periodically searches for object cycles that are inaccessible from the program and deletes them. -
How GC works: It divides objects into generations (0, 1, 2) and checks younger objects more frequently. This optimizes performance.
Example of manually invoking the collector:
import gc
# Invoke garbage collection
collected = gc.collect()
print(f"Objects collected: {collected}")
Thus, Python combines fast reference counting with periodic cycle detection for efficient memory management.