Python Garbage Collection
How Python perform garbage collection ?
The main garbage collection algorithm used by CPython is reference counting. The reference count field can be examined using the sys.getrefcount() function (notice that the value returned by this function is always 1 more as the function also has a reference to the object when called):
class Test:
def __init__(self):
...
>>> t = Test()
>>> sys.getrefcount(t)
2
>>> y = t
3
>>> del y
>>> sys.getrefcount(t)
2
However, simple reference counting can handle conditions such as object self-referencing, because ref count never reaches 0 for such cases. Therfore, cyclic garbage collector is introduced.
Starting in version 3.13, CPython contains two GC implementations:
- The default build implementation relies on the global interpreter lock for thread safety.
- The free-threaded build implementation pauses other executing threads when performing a collection for thread safety.
Both implementations use the same basic algorithms, but operate on different data structures.
What is $(topic) ?
Train of Thoughts
Questions ?
✅ Answer
Deep Dive
