Junior — Middle
Can you explain how the memory management system via references is implemented in Python?
sobes.tech AI
Answer from AI
In Python, memory management is implemented through a reference counting system and a garbage collector for cyclic references.
Each object in memory has a reference count — the number of active references to that object. When a new reference is created, the count increases; when a reference is deleted, it decreases. When the count reaches zero, the object's memory is freed.
However, reference counting alone cannot handle cyclic references (when objects reference each other). For this, Python has an additional garbage collector that periodically searches for and removes such cycles.
Example:
import sys
a = []
print(sys.getrefcount(a)) # Shows the number of references to object a
b = a
print(sys.getrefcount(a)) # The count increases
b = None
print(sys.getrefcount(a)) # The count decreases
Thus, Python efficiently manages memory by freeing objects when they are no longer needed.