Course contentsShow
← Python
Lesson 649 of 1,06010. Advanced Language FeaturesFree lesson

Optimizing Attribute Access with Slots

You will combine the descriptor protocol with __slots__ to minimize memory usage while maintaining granular control over class attribute behavior.

Combining Descriptors with Slots for Precision and Efficiency

In this lesson, you will learn how to unify the memory-saving power of __slots__ with the granular logic control provided by the descriptor protocol.

By default, Python objects store their attributes in a dynamic dictionary called __dict__. While flexible, this consumes significant memory. When you define __slots__ = ('attr_name',), you tell Python to allocate only the exact space required for those specific attributes, effectively disabling the per-instance __dict__.

However, __slots__ alone is passive—it just reserves space. If you want to enforce validation, type-checking, or computed logic for those slots, you must use data descriptors. When you assign a descriptor to a class attribute that is also named in __slots__, Python uses the descriptor’s __get__ and __set__ methods to handle access while still storing the actual data efficiently within the slot space.

Practical Implementation

Consider a scenario where you want a "constrained" attribute that must always be a positive integer, stored efficiently:

class PositiveInt:
    def __set_name__(self, owner, name):
        self.name = f"_{name}"

    def __get__(self, instance, owner):
        return getattr(instance, self.name)

    def __set__(self, instance, value):
        if not isinstance(value, int) or value < 0:
            raise ValueError("Must be a positive integer")
        setattr(instance, self.name, value)

class Product:
    # Reserve specific storage slots
    __slots__ = ('_quantity',)
    
    # Attach the descriptor logic
    quantity = PositiveInt()

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

In this example, the Product instance does not create a __dict__. Instead, the descriptor logic manages the data directly in the _quantity slot. This pattern is powerful because it allows you to build complex, rule-based object models that remain incredibly lightweight, which is critical when you are instantiating thousands or millions of objects in a data pipeline. By mapping descriptors to slots, you gain the "best of both worlds": the runtime safety of logic-controlled attributes and the hardware-level efficiency of static memory allocation.

Key Takeaway: Pairing descriptors with __slots__ allows you to enforce complex attribute rules without the memory overhead of a per-instance __dict__, providing both data integrity and high-performance memory utilization.