pythonintermediate

Optimize Memory with __slots__

Reduce memory usage for classes with many instances using __slots__.

python
import sys

# Without __slots__: each instance has a __dict__
class PointRegular:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

# With __slots__: fixed attribute set, no __dict__
class PointSlotted:
    __slots__ = ('x', 'y', 'z')

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

# Compare memory usage
regular = PointRegular(1.0, 2.0, 3.0)
slotted = PointSlotted(1.0, 2.0, 3.0)

print(f"Regular: {sys.getsizeof(regular) + sys.getsizeof(regular.__dict__)} bytes")
print(f"Slotted: {sys.getsizeof(slotted)} bytes")

# Slotted prevents dynamic attributes
try:
    slotted.w = 4.0  # AttributeError!
except AttributeError as e:
    print(f"Cannot add: {e}")

# Great for millions of instances
points = [PointSlotted(i, i, i) for i in range(1_000_000)]

Use Cases

  • Memory-constrained applications
  • Game entities
  • Large datasets

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.