0Pricing
Python Academy · Lesson

__slots__ and Memory Optimization

Use __slots__ to reduce per-instance memory overhead.

The Default __dict__ Overhead

By default every Python instance stores attributes in a __dict__ dictionary, which has significant memory overhead — typically 200-400 bytes per instance.

import sys

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

p = Point(1, 2)
print(sys.getsizeof(p.__dict__))   # ~200 bytes

Declaring __slots__

Define __slots__ as a sequence of attribute names. Python allocates a fixed-size array instead of a dict, saving memory.

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

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

p = SlottedPoint(1, 2)
print(p.x, p.y)   # 1 2
# p.z = 3   # AttributeError: no __dict__

All lessons in this course

  1. How Python Classes Are Created
  2. Writing Custom Metaclasses
  3. Descriptors: __get__, __set__, __delete__
  4. __slots__ and Memory Optimization
← Back to Python Academy