Advertisement
Advanced Python, Data Types & Structures

How would you implement a custom, memory-efficient data structure using __slots__ instead of a regular class with a __dict__?

Short answer

Declaring __slots__ = ("attr1", "attr2", ...) on a class tells Python to allocate FIXED, pre-defined storage slots for those specific attributes instead of giving each instance a dynamic __dict__ — significantly reducing per-instance memory overhead, especially valuable when…

Save Python mock interview
Advertisement
AModel answer
Declaring __slots__ = ("attr1", "attr2", ...) on a class tells Python to allocate FIXED, pre-defined storage slots for those specific attributes instead of giving each instance a dynamic __dict__ — significantly reducing per-instance memory overhead, especially valuable when creating MANY instances of a small class.
class Point:
    __slots__ = ("x", "y")  # no per-instance __dict__ allocated
    def __init__(self, x, y):
        self.x = x
        self.y = y
    # point.z = 5  # would raise AttributeError -- no __dict__, no arbitrary new attributes
Real-world example
Reducing memory usage significantly when creating millions of small objects, like Point instances in a large point cloud dataset.
Likely follow-ups
  • What capability do you LOSE by using __slots__, like the ability to add new attributes dynamically?
Related topics