Garbage Collection Mechanics & gc.collect()
Reference counting cannot clean circular references (Object A -> Object B -> Object A). Python's cyclic garbage collector detects and purges them with `gc.collect()` 🗑️.
import gc
class Node:
def __init__(self):
self.cycle = self # Self-referencing cycle!
n = Node()
del n # Ref count never hits 0 due to self-reference!
# Force cyclic garbage collection pass:
unreachable = gc.collect()
print(f"Purged unreachable objects: {unreachable} 🗑️")
# 84. Garbage Collection Mechanics & gc.collect() Reference counting cannot clean circular references (Object A -> Object B -> Object A). Python's cyclic garbage collector detects and purges them with `gc.collect()` 🗑️. ```python import gc class Node: def __init__(self): self.cycle = self # Self-referencing cycle! n = Node() del n # Ref count never hits 0 due to self-reference! # Force cyclic garbage collection pass: unreachable = gc.collect() print(f"Purged unreachable objects: {unreachable} 🗑️") ``` Python organizes cyclic memory into three generations (Gen 0, 1, 2). Young objects are inspected frequently; long-lived survivor objects are inspected rarely! 🗑️ --- ### Question Why can't standard reference counting reclaim objects trapped in a circular reference? 🧠 - [ ] a. The mutual references keep the reference counts of the objects at 1 or higher 🗑️ - [ ] b. The operating system locks circular pointers in virtual memory - [ ] c. Circular references convert objects into immutable tuples - [ ] d. Python skips reference decrementing inside class instances --- ### Challenge Import `gc`. Trigger a garbage collection pass with `gc.collect()`. Print whether `gc.isenabled()` is `True`. 🎯 <details> <summary>Solution</summary> ```python import gc gc.collect() print(gc.isenabled()) ``` </details>