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

Managing Instance State via Descriptors

You will store attribute values in a dictionary or instance slot to ensure data remains unique to each object instance.

In this lesson, you will learn how to safely store instance-specific data within descriptors so that different objects don't overwrite each other's values.

The Problem of Shared State

When you define a descriptor as a class attribute, the descriptor instance is shared across every object of your class. If you store a value directly on the descriptor (e.g., self.value = x), every instance of your class will share that same value. This leads to "leaking" data between instances, where changing one object changes them all!

Using the Instance Dictionary

To ensure data remains unique to each object, we use the instance argument passed to the descriptor's __get__ and __set__ methods. We can store the attribute value inside the instance.__dict__ or simply map the instance's unique id() to a dictionary stored within the descriptor.

Here is how you keep state isolated using a dictionary inside the descriptor:

class ManagedAttribute:
    def __init__(self):
        # We store values here, keyed by the instance object
        self._data = {}

    def __get__(self, instance, owner):
        if instance is None: return self
        return self._data.get(instance)

    def __set__(self, instance, value):
        # By using the instance as the key, state stays unique
        self._data[instance] = value

class User:
    name = ManagedAttribute()

# Usage
u1 = User()
u2 = User()

u1.name = "Alice"
u2.name = "Bob"

print(u1.name)  # Output: Alice
print(u2.name)  # Output: Bob

Why This Matters

By using the instance as a key in a storage dictionary (or by setting an attribute directly on the instance object), you decouple the descriptor's logic from the specific data being held. The descriptor acts as the "manager," while the instance acts as the "storage container." This allows your descriptors to be reusable across many instances without any risk of data contamination.

Key Takeaway: To avoid shared state bugs, always store instance-specific data within the descriptor by using the instance object as a key or by modifying the instance itself, rather than storing values on the descriptor instance.