Senior
How does garbage collection work in Python?
sobes.tech AI
Answer from AI
The garbage collector (GC) in Python is primarily based on reference counting. Each object 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.
However, reference counting cannot handle cyclic references (when objects reference each other but are no longer used). For this, Python has an additional module called gc, which periodically runs a cycle detection algorithm and frees objects involved in cycles if they are unreachable from the program.
Example:
import gc
# Enable cyclic garbage collector
gc.enable()
# Run collection manually
gc.collect()
Thus, Python combines fast reference counting for immediate release with periodic collection of cyclic objects to prevent memory leaks.