🚀 Hidden Power Feature: The Descriptor Protocol
(How property, staticmethod, ORMs, cached attributes & a bunch of other “magic” work under the hood)
Most Pythonistas use descriptors every day without realizing it.
If you’ve ever written @property, @classmethod, or imported functools.cached_property, you’re already relying on this protocol. Yet relatively few people know how to create their own descriptors—and that knowledge opens doors to clean APIs, validation, lazy loading, fancy ORM fields, and more.
1. 30-Second Definition
A descriptor is any object that defines one or more of:
If Python finds such an object as a class attribute, it delegates attribute access to those methods.
text
obj.attr → obj.__class__.__dict__["attr"].__get__(obj, obj.__class__)
obj.attr = v → obj.__class__.__dict__["attr"].__set__(obj, v)
del obj.attr → obj.__class__.__dict__["attr"].__delete__(obj)
2. Data vs. Non-Data Descriptors (the precedence rule)
Kind
Implements
Lookup precedence
Data descriptor
__set__ and/or __delete__ (can also have __get__)
Wins over everything, including the instance’s __dict__
Non-data descriptor
Only __get__
Wins over class attributes, but loses to instance attributes
Why you care: caching, overriding & validation behavior depend on which kind you implement.
3. How Attribute Lookup Actually Works (abridged)
If the attribute lives in the class dict and is a data descriptor, call its __get__ / __set__.
Else if the attribute exists in the instance’s __dict__, return that.
Else if the attribute in the class dict is a non-data descriptor, call its __get__.
Else fall back to the plain value from the class or its parents.
If nothing found, raise AttributeError.
Understanding this lookup chain is the key to why the following tricks work.
4. Build Your Own Descriptors
4.1. Validated & Typed Fields
python
class Positive:
def __set_name__(self, owner, name):
self.private_name = '_' + name
def __get__(self, instance, owner):
if instance is None: # accessed from the class?
return self # => return the descriptor itself
return getattr(instance, self.private_name, 0)
def __set__(self, instance, value):
if value <= 0:
raise ValueError("Value must be > 0")
setattr(instance, self.private_name, value)
class BankAccount:
balance = Positive() # plug & play!
acc = BankAccount()
acc.balance = 200
print(acc.balance) # 200
acc.balance = -5 # raises ValueError
• Implements __set__ → data descriptor → prevents users from monkey-patching balance with arbitrary types via acc.__dict__.
4.2. One-Line lazy_property (non-data, so cache can overwrite)
python
class lazy_property:
def __init__(self, func):
self.func = func
self.__name__ = func.__name__
def __get__(self, instance, owner):
if instance is None:
return self # accessed from class
value = self.func(instance)
setattr(instance, self.__name__, value) # store result in __dict__
return value
Usage:
python
class Fibonacci:
@lazy_property
def sequence(self):
print("Expensive computation once!")
return [0, 1, 1, 2, 3, 5, 8]
f = Fibonacci()
f.sequence # prints once
f.sequence # uses cached list
Because this is a non-data descriptor, after first call sequence is written into instance.__dict__; subsequent lookups hit rule #2 and skip __get__.
4.3. Managed “Column” Objects in ORMs (simplified)
python
class Column:
def __init__(self, sql_type):
self.sql_type = sql_type
def __set_name__(self, owner, name):
self.name = name
def __get__(self, instance, owner):
if instance is None:
return self # class-level access returns metadata
return instance.__dict__.get(self.name)
def __set__(self, instance, value):
# could add conversions/validation here
instance.__dict__[self.name] = value
class User:
id = Column("INTEGER PRIMARY KEY")
username = Column("TEXT UNIQUE")
u = User()
u.username = "guido"
print(User.username.sql_type) # metadata at class-level
That’s more or less how SQLAlchemy and Django models wrap database fields!
5. Extra Nuggets Everyone Misses
__set_name__(self, owner, name) (PEP 487, Py3.6+)
Gets called automatically when the owning class is created. Perfect for reading the attribute name without user boilerplate.
Class-level access pattern:
Inside __get__ you receive instance=None when someone does MyClass.attr. Use that to expose metadata or return the descriptor itself.
You can stack descriptors!
A descriptor can return another descriptor, which is how @classmethod wraps the plain function (already a non-data descriptor).
Both staticmethod and classmethod are merely wrappers implementing __get__.
Peeking at classmethod.__get__ reveals great learning material.
6. When Should You Reach For Descriptors?
• Reusable validation (positive numbers, email addresses, non-null).
• Automatic type coercion (e.g., convert to datetime).
• Lazy attributes that should “materialize” only once.
• Building DSLs / internal mini-frameworks (ORMs, settings objects, declarative APIs).
• Caching expensive computations (functools.cached_property is just an optimized C-level version of the lazy example).
If you ever repeated the same property boilerplate across classes, you’re a prime candidate for writing a descriptor.
7. Mini-Cheat Sheet
python
class MyDescriptor:
def __set_name__(self, owner, name):
self.name = name # owner == containing class
def __get__(self, instance, owner):
if instance is None:
return self # class-level access
return instance.__dict__[self.name]
def __set__(self, instance, value):
instance.__dict__[self.name] = value # validation? coercion?
def __delete__(self, instance):
del instance.__dict__[self.name]
Remember:
• Add __set__ → data descriptor → shadows instance dict.
• Omit __set__ → non-data → instance dict can override (handy for cache).
TL;DR
Descriptors power half of the Python “magic” you already love. By mastering them you unlock:
✅ Cleaner, declarative class designs
✅ Practically free validation / caching, no repetitive @property code
✅ Better mental model of why attribute access behaves the way it does
Spend an hour rewriting one of your existing classes with a custom descriptor—you’ll never look at @property the same way again. Happy meta-programming! 🐍