← Home ← Codex ← DEBT
Browse by Category
+ added · updated 7d
← Back to glossary

__slots__ & Memory Optimisation

Python Python 3.0+ Intermediate
debt(d7/e3/b3/t7)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7) — memory-profiler and pympler from detection_hints catch the issue only via runtime profiling, and there's no linter that flags missing __slots__ on heavily-instantiated classes.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3) — quick_fix is adding __slots__ declaration to a class, but it's not purely one line (must enumerate attributes, ensure subclasses also declare it, possibly add __weakref__), making it slightly more than e1.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3) — applies_to is web/cli but the choice is per-class; classes with __slots__ impose constraints (no dynamic attrs, pickle complications, subclass discipline) on that class hierarchy but don't reshape the whole codebase.

t7 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'serious trap' (t7) — misconception and common_mistakes show multiple counterintuitive behaviors: subclasses silently regain __dict__ defeating the optimization, weakref breaks without explicit declaration, and pickle silently misbehaves — these contradict normal Python class inheritance expectations.

About DEBT scoring →

Also Known As

__slots__ slots memory optimisation python

TL;DR

Declaring __slots__ on a class prevents the dynamic __dict__ per instance — reducing memory usage by 40-60% for classes with many instances.

Explanation

By default, each Python object has a __dict__ (a dictionary) storing its attributes — this adds ~200 bytes overhead per instance and allows arbitrary attribute addition. Declaring __slots__ = ('x', 'y') creates fixed-slot descriptors instead, eliminating __dict__. Benefits: 40-60% less memory, faster attribute access (no dict lookup), prevents accidental typo attributes. Trade-offs: no dynamic attributes, no __dict__, no weakref by default (add '__weakref__' to slots). Python 3.10+ dataclasses support slots=True directly.

Common Misconception

__slots__ only saves memory for very large applications — even creating 10,000 instances of a simple Point class uses ~50MB without slots vs ~15MB with slots; the difference is significant for any data-intensive processing.

Why It Matters

A PHP-like active record class with 20 attributes creates millions of objects in batch processing — __slots__ turns a memory-exhausted process into one that runs comfortably.

Common Mistakes

  • Forgetting to add __slots__ to subclasses — a subclass without __slots__ still creates __dict__.
  • Not including '__weakref__' in slots when the class needs to be weakly referenced.
  • Using __slots__ on classes that need dynamic attribute assignment — slots forbid this.
  • Forgetting that __slots__ makes pickle more complex — must implement __getstate__/__setstate__.

Code Examples

✗ Vulnerable
# No slots — each instance has a __dict__:
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

import sys
p = Point(1, 2)
print(sys.getsizeof(p))  # ~48 bytes, plus ~200 bytes for __dict__
# 1 million Points: ~248MB
✓ Fixed
# With __slots__ — fixed layout, no __dict__:
class Point:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

import sys
p = Point(1, 2)
print(sys.getsizeof(p))  # ~56 bytes, no __dict__
# 1 million Points: ~56MB — 4x less memory

# Python 3.10+ dataclass with slots:
from dataclasses import dataclass
@dataclass(slots=True)
class Point:
    x: float
    y: float

Added 16 Mar 2026
Edited 22 Mar 2026
Views 76
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 1 ping W 1 ping T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 2 pings F 1 ping S 0 pings S 1 ping M 2 pings T 0 pings W 2 pings T 0 pings F 1 ping S 1 ping S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 3 pings S 1 ping S 1 ping M 0 pings T 0 pings W
No pings yet today
No pings yesterday
Amazonbot 17 Perplexity 14 Google 5 Ahrefs 4 Scrapy 4 ChatGPT 3 Unknown AI 3 Bing 3 SEMrush 3 Majestic 2 Claude 2 PetalBot 2 Meta AI 1 Sogou 1 Common Crawl 1
crawler 59 crawler_json 5 pre-tracking 1
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Low
⚡ Quick Fix
Add __slots__ to classes with many instances to reduce memory by 20-50% — it prevents dynamic attribute creation and allows Python to store attributes in a fixed-size array instead of a dict
📦 Applies To
python 3.0 web cli
🔗 Prerequisites
🔍 Detection Hints
Class instantiated thousands of times without __slots__; high memory usage from many small object instances; @dataclass without slots=True
Auto-detectable: ✗ No memory-profiler pympler
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: Medium ✗ Manual fix Fix: Medium Context: Class


✓ schema.org compliant