DEV Community

TildAlice
TildAlice

Posted on • Originally published at tildalice.io

Python __slots__ for Memory-Efficient Classes: Interview Essential

Why Most Classes Waste 40% of Their Memory

Every Python instance carries a hidden cost: the __dict__ attribute. It's a full dictionary storing all instance attributes, and dictionaries are memory-hungry. For a simple class with three attributes, you're paying for hash table overhead, pointer storage, and dynamic resizing capacity you'll never use.

__slots__ eliminates that overhead by declaring attributes upfront. Python allocates exactly the space needed—no dictionary, no wasted bytes. The memory savings are dramatic, but the tradeoffs matter more than most tutorials admit.

Here's the memory difference on a trivial class:

import sys

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

class SlottedPoint:
    __slots__ = ('x', 'y', 'z')

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

regular = RegularPoint(1.0, 2.0, 3.0)
slotted = SlottedPoint(1.0, 2.0, 3.0)

print(f"Regular: {sys.getsizeof(regular.__dict__)} bytes (dict only)")
print(f"Slotted: no __dict__ attribute")
print(f"Regular total: ~{sys.getsizeof(regular.__dict__) + 16} bytes")
print(f"Slotted total: ~64 bytes")
Enter fullscreen mode Exit fullscreen mode

Output on Python 3.11:

Regular: 104 bytes (dict only)
Slotted: no __dict__ attribute
Regular total: ~120 bytes
Slotted total: ~64 bytes
Enter fullscreen mode Exit fullscreen mode

Continue reading the full article on TildAlice

Top comments (0)