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 also assumes you know that obj.name goes through object.__getattribute__, which the previous chapter covered.
What a descriptor is
A descriptor is an object, stored as an attribute of a class, whose type defines at least one of three methods: __get__, __set__ or __delete__. When Python finds such an object in a class while looking up or assigning an attribute, it calls these methods instead of returning or replacing the object itself.
| Method | Called when | Signature |
|---|---|---|
| `__get__` | Reading `obj.name` or `Cls.name` | `__get__(self, obj, objtype=None)` |
| `__set__` | Assigning `obj.name = value` | `__set__(self, obj, value)` |
| `__delete__` | Running `del obj.name` | `__delete__(self, obj)` |
The methods must be defined on the descriptor's type, not on the descriptor instance. Python looks them up on the type, so assigning desc.__get__ = ... on one instance has no effect.
The arguments of `__get__`
__get__ receives two pieces of context. obj is the instance the attribute was read from, or None when the read happened on the class itself (Cls.name). objtype is the class. Descriptors usually return self when obj is None, so that Cls.name gives you the descriptor for inspection.
class Verbose:
def __get__(self, obj, objtype=None):
print(f"__get__ obj={obj!r} objtype={objtype.__name__}")
return 42
def __set__(self, obj, value):
print(f"__set__ obj={obj!r} value={value!r}")
def __delete__(self, obj):
print(f"__delete__ obj={obj!r}")
class Demo:
x = Verbose()
def __repr__(self):
return "<Demo>"
d = Demo()
print(d.x)
d.x = 10
del d.x
print(Demo.x)Running this prints:
__get__ obj=<Demo> objtype=Demo
42
__set__ obj=<Demo> value=10
__delete__ obj=<Demo>
__get__ obj=None objtype=Demo
42The last two lines show the class-level read: obj is None.
Where the call happens
The chart is simplified. Whether an instance __dict__ entry is checked first depends on whether the descriptor is a data descriptor, which the next chapter covers.
Descriptor state belongs to the instance
A descriptor object is created once, when the class body runs. Every instance of the class shares it. If __set__ stored the value on the descriptor (self.value = value), all instances would see the same value. Store per-instance data on obj instead, or in a per-instance mapping.
class Shared:
def __get__(self, obj, objtype=None):
return self.value
def __set__(self, obj, value):
self.value = value # wrong: one value for every instance
class Box:
size = Shared()
a, b = Box(), Box()
a.size = 1
b.size = 2
print(a.size) # 2, not 1Calling the protocol by hand
Because the protocol is plain method calls, you can invoke it directly. This is useful for debugging.
class Const:
def __get__(self, obj, objtype=None):
return "constant"
class K:
c = Const()
print(K.__dict__["c"].__get__(K(), K)) # constantExercise
A class defines x = Verbose(), where Verbose defines __get__, __set__ and __delete__. What value does __get__ receive for obj when you run print(Demo.x), and why?
Show answer
It receives None. The attribute is read on the class, not on an instance, so there is no instance to pass. Python still calls __get__, with objtype set to Demo.
Exercise
A descriptor's __set__ runs self.value = value. Two instances of the owning class assign different values. What does each instance read back, and what is the fix?
Show answer
Both read the value assigned last, because the single descriptor object is shared by all instances. Store the value on the instance, for example with setattr(obj, self.private_name, value), or in a per-instance mapping.