Skip to main content
← CONCEPTS / PROGRAMMING-LANGUAGES
An end-to-end domain learning journey

Python __slots__, Reference Cycles
& WeakRef Cache Eviction.

Standard Python instances allocate a 104-byte dict hash table per object and strong caches pin cyclic graphs forever; slots + WeakValueDictionary cut RAM 3x and eliminate leaks.
Start the journey2 sections· Last modified Dec 3, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When optimizing slotted Python classes for weak caches, include '__weakref__' in __slots__ and break parent cycles.

TL;DR30-second simplified summary
▾

Achieves 3x memory reduction and deterministic O(1) refcount reclamation.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
CPython Reference Counting
Frees objects immediately when refcount hits 0 unless trapped in a reference cycle.
Python __dict__ vs C-Struct Slots
Dynamic per-instance hash tables vs fixed-offset descriptor arrays.
Full walkthrough · 2 stages
01
STAGE 01beginner

Replacing __dict__ with Fixed __slots__.

Why this matters: Cut per-instance memory overhead by 3x.

slots stores attributes at fixed C-struct offsets instead of allocating a per-instance hash table.

Before · __dict__ + Strong Cache
After · __slots__ + WeakRef
ChoiceWhat it buysWhat it costs
Standard __dict__ ClassAllows dynamic runtime attributes~152 B/obj; slow hash lookup
__slots__ + __weakref__3x less RAM (~48 B/obj); fast C-offset accessFixed attribute set
import weakref

class GraphNode:
    __slots__ = ("nid", "parent", "__weakref__")
    def __init__(self, nid: int, parent=None):
        self.nid = nid
        self.parent = weakref.ref(parent) if parent is not None else None

CACHE = weakref.WeakValueDictionary()
02
STAGE 02intermediate

Breaking Cycles & Java WeakReference Equivalent.

Why this matters: Compare Python WeakValueDictionary with Java WeakReference caches.

In both Python and Java, weak references allow the runtime to reclaim cached or parent-linked objects once strong references drop.

Engineering Decision Framework
Problem
How to cache 10M small AST nodes in Python without 1.5 GB dict bloat or leaking cyclic objects forever.
Naive Solution
Use a standard Python class and store instances in a global dict.
Why It Fails
Every instance allocates a 104-byte dict, and the global dict keeps refcount >= 1 forever, causing OOM.
Alternatives
Manual cache.pop() + dict, LRU with fixed cap, or slots + weakref parent + WeakValueDictionary.
Engineering Decision
Define slots = ('nid', 'parent', 'weakref'), store parent via weakref.ref, and index via WeakValueDictionary.
Trade-Offs
Disables arbitrary ad-hoc attributes on instances, but cuts RAM 3x and eliminates cyclic GC pauses and cache leaks.
Decision Exercise · Make the Call

You add slots = ('nid', 'parent') to GraphNode, then insert it into WeakValueDictionary. What happens at runtime?

import java.lang.ref.WeakReference;

public final class GraphNode {
    public final int nid;
    public final WeakReference<GraphNode> parent;
    public GraphNode(int nid, GraphNode parent) {
        this.nid = nid;
        this.parent = parent != null ? new WeakReference<>(parent) : null;
    }
}
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why must '__weakref__' be listed in __slots__ when using WeakValueDictionary?

Recommended Learning Flow