{
    "slug": "py_slots",
    "term": "__slots__ & Memory Optimisation",
    "category": "python",
    "difficulty": "intermediate",
    "short": "Declaring __slots__ on a class prevents the dynamic __dict__ per instance — reducing memory usage by 40-60% for classes with many instances.",
    "long": "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.",
    "aliases": [
        "__slots__",
        "slots",
        "memory optimisation python"
    ],
    "tags": [
        "python",
        "performance",
        "memory",
        "oop"
    ],
    "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__."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "py_dataclasses_advanced",
        "py_context_manager_advanced",
        "garbage_collection"
    ],
    "prerequisites": [
        "py_dataclasses",
        "memory_management",
        "py_type_hints"
    ],
    "refs": [
        "https://docs.python.org/3/reference/datamodel.html#slots"
    ],
    "bad_code": "# No slots — each instance has a __dict__:\nclass Point:\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n\nimport sys\np = Point(1, 2)\nprint(sys.getsizeof(p))  # ~48 bytes, plus ~200 bytes for __dict__\n# 1 million Points: ~248MB",
    "good_code": "# With __slots__ — fixed layout, no __dict__:\nclass Point:\n    __slots__ = ('x', 'y')\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n\nimport sys\np = Point(1, 2)\nprint(sys.getsizeof(p))  # ~56 bytes, no __dict__\n# 1 million Points: ~56MB — 4x less memory\n\n# Python 3.10+ dataclass with slots:\nfrom dataclasses import dataclass\n@dataclass(slots=True)\nclass Point:\n    x: float\n    y: float",
    "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",
    "severity": "low",
    "effort": "low",
    "created": "2026-03-16",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/py_slots",
        "html_url": "https://codeclaritylab.com/glossary/py_slots",
        "json_url": "https://codeclaritylab.com/glossary/py_slots.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[__slots__ & Memory Optimisation](https://codeclaritylab.com/glossary/py_slots) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/py_slots"
            }
        }
    }
}