Skip to main content
Albero Academy

Descriptors

The protocol behind properties and ORM fields.

Advanced Python9 min

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:

a reusable validating descriptor
class Positive:
def __set_name__(self, owner, name):
self.name = name # remember the attribute name
def __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] = value
class Product:
price = Positive() # managed by the descriptor
qty = Positive() # reuse it across attributes
p = 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

  1. 01A descriptor customises attribute get/set/delete via __get__/__set__/__delete__.
  2. 02It is assigned as a class attribute and manages instance access.
  3. 03They underpin @property, methods, and ORM/framework field types.
  4. 04Their advantage is reuse — one rule applied across many attributes and classes.
  5. 05You use them constantly but rarely need to write your own.

Finished this chapter?

Mark it complete to track your progress through Python.