Python Descriptors: Data vs Non-Data Lookup
A descriptor is an object that lives on a class and takes over what happens when that name is read, assigned, or deleted through an instance. You already use them every day: property, classmethod, staticmethod, functools.cached_property, and every mapped column in an ORM are descriptors. The protocol deserves close study because attribute lookup is the most frequent operation in any Python program, and once descriptors, instance dictionaries, and inheritance interact, the real lookup order stops matching what most programmers assume from reading ordinary class code.
What You'll Learn
- 1Trace the exact priority order Python uses to resolve an instance attribute
- 2Tell a data descriptor from a non-data descriptor and predict which one wins
- 3Build a validated field that discovers its own attribute name with __set_name__
- 4Write a caching descriptor and decide when its cached value must be dropped
Attribute lookup is a priority order, not a search
When you write user.age, Python does not simply open a dictionary. It walks the method resolution order of type(user) looking for the name age, and along the way it can meet three different kinds of object: a data descriptor, an ordinary value stored in the instance dictionary, and a non-data descriptor or plain class attribute. The rules that combine them are short, but they are absolute, and they explain most "why did my value disappear" bugs in framework code.
Python searches the class hierarchy and the instance dictionary in one pass. If a data descriptor is found anywhere in the MRO, it is called and its result is returned; the instance dictionary is never consulted for that name. If no data descriptor exists, the instance dictionary is checked next, and only when the name is absent there does Python fall back to a non-data descriptor or a plain class attribute. Inheritance therefore does more than add fields â it can silently change which object answers a read, because a subclass that introduces a descriptor with __set__ promotes itself above every stored value of the same name.
The four hooks and what Python passes them
A descriptor is any object that defines at least one of __get__, __set__, or __delete__ and is stored on a class rather than on an instance. A fifth method, __set_name__, is not part of the lookup protocol but is called once during class creation, which makes reusable field declarations possible.
| Hook | Typical signature | Triggered by | Conventional return |
|---|---|---|---|
__get__ | __get__(self, instance, owner) | obj.name or Cls.name | The attribute value |
__set__ | __set__(self, instance, value) | obj.name = value | Nothing |
__delete__ | __delete__(self, instance) | del obj.name | Nothing |
__set_name__ | __set_name__(self, owner, name) | Class creation, exactly once | Nothing |
owner is the class itself, and instance is None when the attribute was read from the class rather than from an object. That difference lets one descriptor serve Product.price to an introspection tool and product.price to application code, and the convention is to return self when instance is None so reflection still sees the field definition.
Why a data descriptor outranks stored data
The defining feature of a data descriptor is that it implements __set__ (or __delete__) in addition to __get__. Because the class-level lookup wins before the instance dictionary is opened, you can validate or coerce every write and guarantee that no code path can smuggle a raw value past your rules.
class Bound:
"""A data descriptor: defines both __get__ and __set__."""
def __set_name__(self, owner, name):
self.public = name
self.private = "_" + name
def __get__(self, instance, owner=None):
if instance is None:
return self
return getattr(instance, self.private, None)
def __set__(self, instance, value):
if not isinstance(value, int) or value < 0:
raise ValueError(f"{self.public} needs a non-negative int")
setattr(instance, self.private, value)
class Account:
balance = Bound()
def __init__(self, balance):
self.balance = balance
a = Account(100)
a.balance = 250
a.__dict__["balance"] = 999 # written directly into the instance dict
print(a.balance) # 250 â the dictionary entry is ignored
That last line is the whole point. Assigning into a.__dict__ stores a value under the same name, yet reads still return 250, because Bound defines __set__ and therefore outranks the instance dictionary. Debuggers, copy.copy, and libraries that poke at __dict__ all produce surprises of exactly this shape.
Functions are descriptors, which is why methods bind
Ordinary functions define only __get__, which makes them non-data descriptors. That single fact explains bound methods, the meaning of self, and why assigning a function to an instance attribute behaves differently from assigning it to the class.
class Greeter:
def greet(self, name):
return f"hello {name}"
g = Greeter()
print(g.greet) # bound method
print(Greeter.greet) # plain function
print(Greeter.greet.__get__(g, Greeter)("Ada")) # hello Ada
g.greet = lambda name: f"hi {name}" # instance dict wins now
print(g.greet("Ada")) # hi Ada
Because a function has no __set__, the instance dictionary beats it, so the hand-assigned lambda takes over for that one object. This is the mechanism behind per-instance method overrides and behind unittest.mock.patch.object replacing a method temporarily. It is also why a function stored in a list or attached to an object does not bind: only names looked up through a class go through __get__.
set_name makes field declarations reusable
Before __set_name__ existed, a descriptor had to be told its attribute name as a constructor argument, so every class body repeated the name in two places and renaming one copy silently broke storage. Python now calls __set_name__(owner, name) once on every descriptor found in a class body, passing the class and the name it was assigned to.
The call happens while the class statement is executing, so the descriptor can prepare per-field state such as a private storage key, a validation range keyed by field, or a column name passed to a query builder. It also fires for descriptors inherited from base classes only when they are assigned in the subclass body â inherited descriptors keep the name they were first declared with, which is why storing the name on the descriptor rather than recomputing it later is the safe habit.
Caching descriptors and the invalidation trap
A caching descriptor follows functools.cached_property: implement __get__ only, then park the computed result in the instance dictionary under a private key. Because the descriptor is non-data, the private key does not collide with the public name, so reads keep flowing through __get__ and land on the cache.
class Cached:
def __set_name__(self, owner, name):
self.public = name
self.store = "_cached_" + name
def __get__(self, instance, owner=None):
if instance is None:
return self
cache = instance.__dict__
if self.store not in cache:
cache[self.store] = instance.compute(self.public)
return cache[self.store]
def __delete__(self, instance):
instance.__dict__.pop(self.store, None)
class Report:
total = Cached()
def compute(self, name):
print(f"recomputing {name}")
return sum(range(10))
r = Report()
print(r.total) # recomputing total
print(r.total) # silent, served from cache
del r.total # cached value dropped
print(r.total) # recomputing total
The design question is never how to cache; it is when to invalidate. If the inputs behind compute change â a file on disk, a row in a table, a user setting â nothing in this descriptor knows about it, so it will happily serve a stale answer forever. Tie invalidation to an explicit __delete__, a version counter on the instance, or simply do not cache anything whose inputs are not owned by the object.
Descriptors already shipping in the standard library
| Name | Kind | Defines | Practical consequence |
|---|---|---|---|
property | Data descriptor | __get__, __set__, __delete__ | Cannot be shadowed by writing to the instance |
classmethod | Non-data descriptor | __get__ only | Instance dictionary can hold an override |
staticmethod | Non-data descriptor | __get__ only | Returns the plain function, no binding |
functools.cached_property | Non-data descriptor | __get__ only | Stores its result in the instance dictionary |
| Plain function | Non-data descriptor | __get__ only | Produces a bound method on access |
Notice that only property is a data descriptor. Everything else in the table loses to an instance dictionary entry of the same name, which is precisely why cached_property can store its value on the instance at all, and why you can replace a bound method with a plain attribute on a single object.
Where the protocol trips people up
Three edges bite in production. A descriptor stored in an instance dictionary is never consulted, so a subclass that assigns self.price = 5 bypasses validation entirely unless the descriptor also defines __set__ on a class attribute the instance cannot shadow. Second, descriptors that hold references to their instances leak memory if they keep those references in a long-lived structure; store the value on the instance and let the descriptor stay stateless. Third, descriptors on classes that use __slots__ behave differently, because there is no instance dictionary to fall back on and a non-data descriptor without a slot has nowhere to put a cached result.
Common Mistakes
Assuming that writing into the instance dictionary changes what a descriptor returns
Fix: Data descriptors win over the instance dictionary; read the class first to know whether __set__ exists
Caching a computed value with no way to invalidate it
Fix: Expose __delete__ or a version stamp, and document which inputs invalidate the cached result
Passing the attribute name to the descriptor constructor so it knows where to store data
Fix: Implement __set_name__, which Python calls automatically during class creation and keeps correct under renaming
Holding a reference to the owning instance inside the descriptor
Fix: Keep the descriptor stateless and store per-instance data on the instance, otherwise long-lived class attributes pin objects in memory
Best Practices
- Return self from __get__ when instance is None so introspection and documentation tools still see the declaration
- Define __set__ on any descriptor whose values must be validated, because only data descriptors cannot be shadowed
- Give every cached descriptor an explicit invalidation path before you ship it
- Write a focused unit test that assigns, reads, deletes, and subclasses the descriptor in isolation
- Reach for a plain property or a helper function first; descriptors are the tool for reusable, parameterised behaviour across many fields
Interview Questions
Q1: What makes a descriptor a data descriptor, and why does that matter?
Implementing __set__ or __delete__ in addition to __get__. Data descriptors are looked up before the instance dictionary, so they cannot be bypassed by writing an attribute directly on the object; non-data descriptors lose to that entry.
Q2: Why does a method bind to an instance automatically?
Functions are non-data descriptors. Reading obj.method triggers the function's __get__ with the instance, which returns a bound method object that carries the instance as the first argument.
Q3: When is __set_name__ called, and what is it for?
Once, while the class statement executes, for each descriptor in the class body. It receives the owner class and the attribute name, which lets a descriptor capture its own storage key without the name being repeated as a constructor argument.
Q4: Why can functools.cached_property store its result on the instance?
It defines only __get__, so it is a non-data descriptor. The cached entry lives in the instance dictionary under a different name, and reads of the public name still route through __get__ to find it.
Key Takeaways
- Attribute resolution is a priority order: data descriptor, then instance dictionary, then non-data descriptor or class attribute
- Defining __set__ is what promotes a descriptor above stored data and makes validation unavoidable
- Functions, classmethod, staticmethod and cached_property are all non-data descriptors, which is why they lose to instance entries
- __set_name__ is called once at class creation and removes the need to repeat attribute names in constructors
- A cache without an invalidation rule is a bug that will serve stale data on schedule