The Descriptor Protocol: __get__, __set__ & Data Descriptors
Python's `@property`, `@classmethod`, and ORM attributes are powered by the Descriptor Protocol. Implementing `__get__`, `__set__`, or `__delete__` overrides instance `__dict__` lookups, intercepting attribute reads and writes with zero runtime boilerplate ⚙️🔍.
class PositiveNumber:
def __set_name__(self, owner, name):
self.field = f"_{name}"
def __get__(self, instance, owner):
if instance is None: return self
return getattr(instance, self.field, 0)
def __set__(self, instance, value):
if value < 0:
raise ValueError("Value cannot be negative! 🛑")
setattr(instance, self.field, value)
class InventoryItem:
stock = PositiveNumber()
def __init__(self, count):
self.stock = count
item = InventoryItem(25)
print(f"Validated Stock: {item.stock} 🚀")
# 81. The Descriptor Protocol: __get__, __set__ & Data Descriptors Whenever you write `obj.x = 10`, Python doesn't just blindly stick `'x': 10` into `obj.__dict__`. It executes a prioritized attribute lookup sequence governed by the Descriptor Protocol 🛑. ```python # The Attribute Resolution Hierarchy: # 1. Data Descriptor (__get__ AND __set__ defined on class) -> WINS OVER __dict__! # 2. Instance dictionary: obj.__dict__['x'] # 3. Non-Data Descriptor (ONLY __get__ defined, like methods and classmethods) # 4. Class dictionary: type(obj).__dict__['x'] # 5. __getattr__() fallback ``` ### The Descriptor Methods 1. **`__set_name__(owner, name)`** (Python 3.6+): Automatically captures the variable name assigned in the class body, eliminating manual string passing. 2. **`__get__(instance, owner)`**: Called when reading `instance.attribute`. If accessed on the class itself (`Owner.attribute`), `instance` is `None`. 3. **`__set__(instance, value)`**: Called when assigning `instance.attribute = value`. Defining `__set__` promotes the object to a **Data Descriptor**, meaning it intercepts assignments before `instance.__dict__` can ever be touched ⚙️🔍. --- ### Interactive Pop-Quiz 🧠 #### What distinguishes a 'Data Descriptor' from a 'Non-Data Descriptor' in Python attribute resolution precedence? - [ ] A Data Descriptor implements `__set__` (or `__delete__`), taking precedence over the instance's own `__dict__` ⚙️ - [ ] A Data Descriptor can only store binary float values - [ ] A Non-Data Descriptor runs inside C extension modules exclusively - [ ] A Data Descriptor is executed at build time by the compiler --- ### Practical Challenge 🎯 Implement a descriptor `TypedString` enforcing that assigned values must be `str`. In `__set_name__`, store `_attr`. In `__set__`, raise `TypeError` if value is not `str`. Create class `UserProfile` with `username = TypedString()`. Assign `'dev_alice'`. Verify assigning `12345` raises `TypeError`. Print `'DESCRIPTOR_VALIDATED'`. <details> <summary>Solution</summary> ```python class TypedString: def __set_name__(self, owner, name): self.attr = f"_{name}" def __get__(self, instance, owner): if instance is None: return self return getattr(instance, self.attr, None) def __set__(self, instance, value): if not isinstance(value, str): raise TypeError("Must be a string") setattr(instance, self.attr, value) class UserProfile: username = TypedString() def __init__(self, name): self.username = name u = UserProfile("dev_alice") assert u.username == "dev_alice" caught = False try: u.username = 12345 except TypeError: caught = True assert caught is True print("DESCRIPTOR_VALIDATED") ``` </details>