The idea to keep with you
When refactoring cyclic Python trees, use __slots__ with '__weakref__' and weakref.ref parent pointers.
TL;DR30-second simplified summary▾
Drops RAM from 1.52 GB to 0.48 GB with zero leaks.
Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Python __slots__
Eliminates per-instance dict hash tables.
Reference Cycles & WeakRefs
Breaks strong cycles for O(1) refcount reclamation.
Full walkthrough · 2 stages
01
STAGE 01intermediate
Pinpointing __dict__ Bloat & Strong-Cache Cycles.
Why this matters: Identify why refcounting fails to free dead graph subtrees.
Strong parent<->child references keep refcount >= 1, and global dict caches pin dead nodes permanently.
Before · 10M __dict__ + Strong Cache
After · 10M __slots__ + WeakRef
| Choice | What it buys | What it costs |
|---|---|---|
| Strong Cache + __dict__ | Zero boilerplate | 1.5 GB bloat + permanent leak |
| __slots__ + WeakValueDictionary | 3x RAM reduction + auto-eviction | Must list '__weakref__' in __slots__ |
# Refactored leak-free, slotted node
import weakref
class AstNode:
__slots__ = ("nid", "children", "_parent", "__weakref__")
def __init__(self, nid: int, parent=None):
self.nid = nid
self.children = []
self._parent = weakref.ref(parent) if parent is not None else None
02
STAGE 02intermediate
Verifying Zero Leaks in Python & Java.
Why this matters: Confirm deterministic reclamation when strong roots drop.
Once the caller drops the root reference, WeakValueDictionary automatically removes the entry without manual eviction.
Engineering Decision Framework
- Problem
- Eliminate 1.5 GB RAM bloat and multi-second GC pauses in a 10M-node Python graph service.
- Naive Solution
- Call gc.collect() in a background timer while keeping dict and strong dict caches.
- Why It Fails
- Manual gc.collect() worsens stop-the-world pauses, and strong dict caches still leak memory forever.
- Alternatives
- Periodic gc.collect(), LRU cap with dict, or slots + weakref parent + WeakValueDictionary.
- Engineering Decision
- Refactor nodes to slots = ('nid', 'children', '_parent', 'weakref') with weakref parent pointers and WeakValueDictionary.
- Trade-Offs
- Requires unwrapping weakref parent() on access, but cuts RAM 3x and eliminates cyclic GC pauses.
Decision Exercise · Make the Call
After refactoring AstNode to slots, gen-2 GC pauses still occur because parent and child hold strong references to each other. What fixes this?
// Java equivalent using WeakHashMap / WeakReference
Map<Integer, WeakReference<AstNode>> cache = new HashMap<>();
Practice · Explain the consequences
Practice: Make the trade-off yourself.
Question 1 of 3
Score: 0/3Why does gc.disable() cause an OOM if parent<->child strong cycles exist?
Recommended Learning Flow