Sub topic 4
The descriptor protocol
This chapter assumes you can write Python classes, know the difference between instance and class attributes, and have used special (dunder) methods. It builds on the earlier chapters about __dict__, the MRO, and object.__getattribute__. Here we define the protocol itself. The next chapter covers which descriptors win over instance attributes.
What a descriptor is
A descriptor is an object that defines at least one of three methods: __get__, __set__, or __delete__. When such an object is stored as an attribute of a class, Python calls those methods instead of returning or replacing the object. The attribute access is delegated to the descriptor.
Descriptors are the mechanism behind functions becoming methods, property, classmethod, staticmethod, __slots__, and functools.cached_property. Each of these uses the protocol described here.
The three methods
| Method | Signature | Triggered by | Return value |
|---|---|---|---|
| `__get__` | `__get__(self, obj, objtype=None)` | `obj.name` or `Cls.name` | Becomes the result of the attribute access |
| `__set__` | `__set__(self, obj, value)` | `obj.name = value` | Ignored |
| `__delete__` | `__delete__(self, obj)` | `del obj.name` | Ignored |
In every signature, self is the descriptor object. obj is the instance the attribute was accessed through. objtype is the class, which in __get__ is the type of the instance.
A tracing descriptor makes the calls visible:
class Trace:
def __get__(self, obj, objtype=None):
kind = "instance" if obj is not None else "class"
print(f"get via {kind} of {objtype.__name__}")
return 42
def __set__(self, obj, value):
print(f"set to {value!r}")
def __delete__(self, obj):
print("delete")
class A:
x = Trace()
a = A()
print(a.x) # get via instance of A, then 42
print(A.x) # get via class of A, then 42
a.x = 5 # set to 5
del a.x # deleteThe descriptor Trace() lives in the class namespace A.__dict__["x"]. The instance a never stores anything, and every operation goes through the descriptor.
Access through the class: obj is None
__get__ is also called when you access the attribute on the class itself. In that case obj is None and objtype is the class. The call A.x above runs Trace.__get__(descriptor, None, A).
Most descriptors that return a per-instance value need to handle this case. A common convention is to return the descriptor itself:
class Named:
def __get__(self, obj, objtype=None):
if obj is None:
return self
return "value for an instance"
class B:
n = Named()
print(B.n) # the Named object, useful for introspection
print(B().n) # value for an instanceReturning self lets tools such as help() and documentation generators find the descriptor. If your __get__ only works with an instance, accessing B.n without this check raises a confusing error, usually an AttributeError or TypeError from using None as an instance.
__set__ and __delete__ only see instances
__set__ and __delete__ have no objtype parameter, and they never run for class-level assignment. Assigning to the class replaces the descriptor:
class Trace:
def __get__(self, obj, objtype=None):
return 42
def __set__(self, obj, value):
print("set called")
class A:
x = Trace()
a = A()
a.x = 1 # set called
A.x = 99 # no __set__ call: the class attribute is replaced
print(A.x) # 99
print(a.x) # 99Setting an attribute on a class is handled by type.__setattr__, which writes into the class __dict__. It does not consult descriptors stored in that same dictionary. To intercept class-level assignment you need a metaclass, covered in a later chapter.
Who calls the methods
User code never calls __get__ in normal use. object.__getattribute__ does, at the point in the lookup where it has found an attribute on the class. The sequence for a.x looks like this:
This chapter covers only the "call __get__" step. The full order of checks, including the instance __dict__, is the topic of the lookup-order chapter.
The protocol is checked on the type
Python looks for __get__, __set__, and __delete__ on the type of the attribute object, not on the object itself. Two consequences follow.
First, a descriptor only takes effect when it is stored in a class. Putting the same object in an instance __dict__ makes it an ordinary value:
class Trace:
def __get__(self, obj, objtype=None):
return 42
class A:
pass
a = A()
a.__dict__["y"] = Trace()
print(type(a.y).__name__) # Trace, not 42Second, attaching __get__ to a single descriptor instance does nothing, because the lookup uses the class Trace:
class Plain:
pass
p = Plain()
p.__get__ = lambda obj, objtype=None: 42
class A:
x = p
print(type(A().x).__name__) # PlainThe instance-level __get__ is ignored. To make an object a descriptor, define the methods in its class body.
Calling the methods directly
Because __get__ is an ordinary method, you can call it yourself. This is useful for debugging and for understanding what Python does:
class Trace:
def __get__(self, obj, objtype=None):
return ("get", obj, objtype)
class A:
x = Trace()
a = A()
raw = A.__dict__["x"] # the descriptor itself, with no __get__ call
print(raw.__get__(a, A)) # same result as a.x
print(raw.__get__(None, A)) # same result as A.x
print(a.x == raw.__get__(a, A)) # TrueReading from A.__dict__ (or vars(A)) bypasses the protocol, which makes it the standard way to inspect the descriptor without triggering it.
Common errors
- Forgetting the
obj is Nonecase.A.xcalls__get__(None, A). Handle it or accept that class access fails. - Expecting
__set__to run onA.x = value. It does not. Class assignment replaces the descriptor. - Defining only
__set__. Writes are intercepted, but reads do not call anything. Reading then returns the instance__dict__entry if there is one, or the descriptor object itself. If you want to validate and also read, define__get__too. - Putting the descriptor in
__init__. Writingself.price = Positive()stores the descriptor object as plain instance data and never triggers the protocol. Create descriptors in the class body. - Adding methods to an instance. Assigning
__get__to a descriptor instance has no effect, as shown above. Define it on the class. - Ignoring return values of
__set__. Python discards them. To reject a value, raise an exception.
Descriptors and shared state
A descriptor is created once, when the class body runs, and every instance of the class shares it. Anything you store on self inside a descriptor method is therefore shared by all instances:
class Counter:
def __init__(self):
self.value = 0 # shared by every instance
def __get__(self, obj, objtype=None):
return self.value
def __set__(self, obj, value):
self.value = value
class Box:
size = Counter()
b1, b2 = Box(), Box()
b1.size = 10
print(b2.size) # 10, not 0Per-instance data must be stored on obj, for example in obj.__dict__ or under a private attribute name. The __set_name__ hook, covered in a later chapter, is the clean way to learn which name to use.
Summary of the protocol
- A descriptor is an object whose type defines
__get__,__set__, or__delete__. - It is activated only when stored as an attribute of a class.
__get__(self, obj, objtype)receivesobj=Nonefor class access.__set__and__delete__run only for instance access. Class-level assignment and deletion replace or remove the descriptor.- The descriptor object is shared by all instances, so per-instance state belongs on
obj.
Exercise
A class A has a descriptor stored as the class attribute x, with _get, set and delete defined. Which arguments does Python pass to get_ for the expression A.x, and what happens if the code A.x = 5 runs?
Show answer
A.x calls _get(descriptor, None, A), so obj is None and objtype is A. The assignment A.x = 5 does not call set. It goes through type.setattr, which replaces the descriptor in A.dict_ with the integer 5.
Exercise
What does this code print, and why? class D: def _get_(self, obj, objtype=None): return "from descriptor" class A: pass a = A() a.item = D() print(a.item)
Show answer
It prints the repr of the D object, such as <_main.D object at 0x...>. The descriptor is stored in the instance dict_, not in the class, so the protocol is not invoked and the object is returned as ordinary data.