A descriptor is an object that customises what happens when you get, set, or delete an attribute on another object. It's an advanced mechanism, but an important one: it's exactly what @property, methods, and ORM/framework fields are built on.
The descriptor protocol
A descriptor defines any of __get__, __set__, __delete__, and is assigned as a class attribute:
class Positive:def __set_name__(self, owner, name):self.name = name # remember the attribute namedef __get__(self, obj, objtype=None):return obj.__dict__[self.name]def __set__(self, obj, value):if value < 0:raise ValueError("must be positive")obj.__dict__[self.name] = valueclass Product:price = Positive() # managed by the descriptorqty = Positive() # reuse it across attributesp = Product()p.price = 10 # OK — goes through __set__# p.price = -1 # ValueError
Why they exist
The win over @property is reusability: one descriptor class enforces the same rule on many attributes across many classes, instead of repeating a property definition each time. It's how validation, type-checking and lazy computation get factored out in libraries.
Key takeaways
- 01A descriptor customises attribute get/set/delete via __get__/__set__/__delete__.
- 02It is assigned as a class attribute and manages instance access.
- 03They underpin @property, methods, and ORM/framework field types.
- 04Their advantage is reuse — one rule applied across many attributes and classes.
- 05You use them constantly but rarely need to write your own.
