__slots__ & Memory Optimization

Published by Brayan K

__slots__ is a class declaration that lists exactly which attributes instances may have, letting Python drop the per-instance __dict__ and store those attributes in fixed slots — making each object smaller and attribute access a touch faster.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A storage layout is not an immutability or type rule

Slots declare storage for named attributes. In a class whose bases do not provide an instance dictionary, they can avoid that dictionary and prevent arbitrary new attributes. The actual memory saving and access speed depend on the interpreter, inheritance and workload; measure your application before treating slots as a performance improvement.

class Point:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y

point = Point(2, 3)
print(point.x, point.y)
print(hasattr(point, "__dict__"))
point.x = "changed"
print(point.x)
try:
    point.label = "A"
except AttributeError as error:
    print(type(error).__name__)
print(hasattr(point, "label"))

# ✅ Expected output:
# 2 3
# False
# changed
# AttributeError
# False

The x slot can be reassigned, and its value can even change type. An extra label is rejected because this object has no storage for it. Attribute-assignment error wording differs across Python versions, so the example reports the error type and whether the assignment succeeded. Validation is a separate job covered by Properties & Descriptors.

class Point:
    __slots__ = ("x", "y")

point = Point()
point.x = 2
point.y = 3
print(vars(point))

# ✅ Expected error:
# TypeError: vars() argument must have __dict__ attribute

Declaring a slot does not initialize its value

class Point:
    __slots__ = ("x", "y")

point = Point()
print(hasattr(point, "x"))
point.x = 2
print(hasattr(point, "x"))
print(point.x)

# ✅ Expected output:
# False
# True
# 2

The declaration reserves the field; the initializer supplies the value. Missing initialization can therefore look like a missing attribute even when the name is present in __slots__. Put ordinary defaults in __init__ rather than binding a class variable with the same name as a slot.

class Point:
    __slots__ = ("x",)
    x = 0

# ✅ Expected error:
# ValueError: 'x' in __slots__ conflicts with class variable

Python creates descriptors for the slot names. A class assignment to the same name would conflict with that descriptor. This is why a slot declaration and a class-level default cannot simply be combined in this way. For generated initialization and field defaults, see Data Classes & Advanced Class Patterns.

Inheritance can bring the instance dictionary back

class Base:
    __slots__ = ("x",)

class FlexibleChild(Base):
    pass

class TightChild(Base):
    __slots__ = ("y",)

class SameFields(Base):
    __slots__ = ()

flexible = FlexibleChild()
flexible.note = "extra"
tight = TightChild()
tight.x = 1
tight.y = 2
print(hasattr(flexible, "__dict__"), flexible.note)
print(hasattr(tight, "__dict__"), tight.x, tight.y)
print(hasattr(SameFields(), "__dict__"))

# ✅ Expected output:
# True extra
# False 1 2
# False

An empty slots declaration adds no fields while retaining the base’s storage restriction. A subclass that omits slots normally gains an instance dictionary. Declare only new field names in a slotted subclass; repeating a base slot name can obscure the inherited storage instead of extending it cleanly.

class FlexibleBase:
    pass

class Child(FlexibleBase):
    __slots__ = ("x",)

item = Child()
item.x = 1
item.note = "still allowed"
print(hasattr(item, "__dict__"))
print(item.note)
print(sorted(vars(item)))

# ✅ Expected output:
# True
# still allowed
# ['note']

The base already provides dynamic storage. Adding a slot on Child does not take that storage away. Inspect the inheritance chain before assuming that the presence of __slots__ means instances have no dictionary. Ordinary inheritance behavior is explained in Inheritance and Polymorphism.

Dynamic attributes and weak references are explicit options

class FlexiblePoint:
    __slots__ = ("x", "__dict__")

point = FlexiblePoint()
point.x = 2
point.label = "A"
print(point.x, point.label)
print(sorted(vars(point)))

# ✅ Expected output:
# 2 A
# ['label']

The slot-backed x is not an entry in the instance dictionary; label is. Including __dict__ restores flexibility and changes the memory tradeoff. It is not evidence that every slotted field was copied into a dictionary.

import weakref

class Point:
    __slots__ = ("x",)

point = Point()
weakref.ref(point)

# ✅ Expected error:
# TypeError: cannot create weak reference to 'Point' object
import weakref

class Point:
    __slots__ = ("x", "__weakref__")

point = Point()
point.x = 2
reference = weakref.ref(point)
print(reference() is point)
print(hasattr(point, "__dict__"))

# ✅ Expected output:
# True
# False

Add __weakref__ only when the base does not already provide that support. Weak references and object lifetime are covered more broadly in Memory Management & Garbage Collection Internals. Here the check concerns which layout allows the reference to be created.

Measure the objects you actually keep

Slots can be useful when a program retains many small instances with a stable set of fields. They also restrict tools that expect vars(instance) or a writable __dict__, including some serializers and caches. A computed property can work with a slot-backed input; a cache that stores itself in __dict__ requires that storage to exist.

Do not compare only the shallow size of an ordinary instance with a slotted instance and call that total application memory. Separately allocated dictionaries, referenced values, shared objects and allocation behavior affect the total. Use representative object counts and a memory profiler, and compare the same workload. This lesson shows storage behavior without promising fixed byte savings or timing figures.

Complete a slotted record and its computed value

Declare two fields and initialize both. The property should compute their product without adding a cached field. Confirm that changing one field updates the computed value and that the instance still has no dictionary.

class Grid:
    ___ = ("rows", "columns")

    def __init__(self, rows, columns):
        self.rows = rows
        self.___ = columns

    @property
    def cells(self):
        return self.rows * self.___

grid = Grid(2, 3)
print(grid.cells)
grid.rows = 4
print(grid.cells)
print(hasattr(grid, "__dict__"))

# 👉 replace ___ with __slots__
# 👉 replace ___ with columns
# 👉 replace ___ with columns

# ✅ Expected output:
# 6
# 12
# False

Extend a record without reopening dynamic storage

Create a slotted BaseRecord with a name and a slotted ScoredRecord subclass that adds only score. Initialize both fields, using the base initializer for name. Add a property label that combines the current name and score. Construct Asha with score 7, print the label, update the score to 9 and print it again. Confirm the instance has no __dict__, then attempt an undeclared extra attribute and report the exception type without relying on version-specific wording.

class BaseRecord:
    __slots__ = ("name",)

    def __init__(self, name):
        self.name = name

class ScoredRecord(BaseRecord):
    __slots__ = ("score",)

    def __init__(self, name, score):
        super().__init__(name)
        self.score = score

    @property
    def label(self):
        return f"{self.name}: {self.score}"

record = ScoredRecord("Asha", 7)
print(record.label)
record.score = 9
print(record.label)
print(hasattr(record, "__dict__"))
try:
    record.extra = "unexpected"
except AttributeError as error:
    print(type(error).__name__)

# ✅ Expected output:
# Asha: 7
# Asha: 9
# False
# AttributeError

The subclass names only its additional field. Both values remain writable because slots control storage names, not mutability. If score needs a range or type rule, that validation must be designed separately.

Practice quiz

What does this program print? class Item: __slots__ = ("value",) x = Item() x.value = 1 x.value = "new" print(x.value) print(hasattr(x, "__dict__"))

  • 1 False
  • new True
  • new False
  • AttributeError

Answer: new False. Slots do not freeze a value or enforce its type.

What does this program print? class Item: __slots__ = ("value",) x = Item() print(hasattr(x, "value"))

  • False
  • True
  • None
  • 0

Answer: False. Declaring the slot does not assign its initial value.

What does this program print? class Base: __slots__ = ("x",) class Child(Base): pass print(hasattr(Child(), "__dict__"))

  • False
  • None
  • TypeError
  • True

Answer: True. A subclass without its own slots declaration normally gains a dictionary.

What does this program print? class Base: __slots__ = ("x",) class Child(Base): __slots__ = () print(hasattr(Child(), "__dict__"))

  • True
  • False
  • None
  • TypeError

Answer: False. An empty declaration adds no storage and preserves this dictionary-free layout.

What does this program print? class Base: pass class Child(Base): __slots__ = ("x",) c = Child() c.note = "extra" print(c.note) print(hasattr(c, "__dict__"))

  • extra False
  • AttributeError
  • extra True
  • None True

Answer: extra True. The base already supplies a dictionary; child slots do not remove it.

What does this program print? class Item: __slots__ = ("value", "__dict__") x = Item() x.value = 1 x.note = "A" print(sorted(vars(x)))

  • ['note']
  • ['note', 'value']
  • ['value']
  • []

Answer: ['note']. The slot-backed value is separate from the dynamic dictionary entry.

Which special slot enables weak references when a base does not provide them?

  • __dict__
  • __weakref__
  • __iter__
  • __size__

Answer: __weakref__. The object layout needs weak-reference support.

Which conclusion can be drawn from hasattr(obj, "__dict__") returning False?

  • The object is immutable
  • Its values have fixed types
  • It is always faster than every ordinary object
  • It has no instance attribute dictionary

Answer: It has no instance attribute dictionary. That structural fact alone does not establish immutability, types or performance.

Continue this course

Related lessons