Sub topic 16
Descriptors: reusable attribute behavior
This chapter assumes you know how to define classes, read and set instance attributes, and use @property. It also assumes you have read the earlier chapters on __getattr__ and dynamic attribute access.
What a descriptor is
A descriptor is an object that lives as a class attribute and defines at least one of __get__, __set__ or __delete__. When you read or write an attribute with that name on an instance, Python calls these methods instead of touching the instance dictionary directly.
Descriptors are the mechanism behind property, classmethod, staticmethod and ordinary methods. Writing your own lets you define attribute behavior once and reuse it across many attributes and classes. A property is tied to one attribute of one class. A descriptor class is not.
| 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)` |
| `__set_name__` | The class body finishes, once per descriptor | `__set_name__(self, owner, name)` |
A reusable validator
The class below checks that a value is positive. It is written once and can be attached to any number of attributes.
class Positive:
def __set_name__(self, owner, name):
self.private_name = '_' + name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self.private_name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError('value must be positive')
setattr(obj, self.private_name, value)
class Item:
price = Positive()
def __init__(self, price):
self.price = price
item = Item(10)
print(item.price) # 10
try:
item.price = -1
except ValueError as e:
print(e) # value must be positive
print(vars(item)) # {'_price': 10}Three details matter here.
__set_name__runs automatically when the classItemis created. Python passes the attribute name ('price'), so the descriptor can derive a storage name ('_price') without you repeating the name by hand.__get__receivesobj=Nonewhen the attribute is read on the class itself, as inItem.price. Returningselfin that case is the convention. It lets tools andhelp()see the descriptor.- The value is stored on the instance under a different name. If the descriptor stored it under
'price'withsetattr, the assignment would call__set__again and recurse forever.
The __init__ assignment self.price = price also goes through __set__. This means the constructor validates too, with no extra code.
Where descriptors fit in attribute lookup
Python decides what obj.name returns by looking at the class first, then the instance. A descriptor that defines __set__ or __delete__ is a data descriptor. One that defines only __get__ is a non-data descriptor. The two kinds sit at different places in the lookup order.
The practical consequences:
- A data descriptor wins over anything in the instance dictionary. This is why
Positivealways validates, even if some code writesitem.__dict__['price'] = -5. The stored value there would simply be ignored on read. - A non-data descriptor loses to the instance dictionary. Writing to the instance shadows it.
- Functions are non-data descriptors. Their
__get__returns a bound method, which is howselfgets filled in.
A non-data descriptor: compute once, then cache
Because a non-data descriptor loses to the instance dictionary, it can compute a value on first access and then step aside. The standard library's functools.cached_property works this way.
class Lazy:
def __init__(self, func):
self.func = func
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
value = self.func(obj)
obj.__dict__[self.name] = value # shadows this descriptor from now on
return value
class Circle:
def __init__(self, r):
self.r = r
@Lazy
def area(self):
print('computing')
return round(3.14159 * self.r ** 2, 2)
c = Circle(2)
print(c.area) # computing, then 12.57
print(c.area) # 12.57, with no second "computing"The first read runs __get__ and writes the result into c.__dict__['area']. On the second read, Python finds the instance entry before it reaches the non-data descriptor. If Lazy defined __set__, the cache would never be reached, because every read would go through __get__ again.
Common errors
Storing state on the descriptor
A descriptor object is shared by every instance of the class. This version looks fine and is wrong:
class BrokenPositive:
def __get__(self, obj, objtype=None):
return self.value
def __set__(self, obj, value):
if value <= 0:
raise ValueError('value must be positive')
self.value = value # one slot for ALL instances
class Box:
width = BrokenPositive()
a, b = Box(), Box()
a.width = 5
b.width = 9
print(a.width) # 9, not 5Store per-instance data on the instance, as Positive does with setattr(obj, self.private_name, value). Keying a dictionary on the instance is another option, but a plain dict keeps the instances alive. A weakref.WeakKeyDictionary avoids that, and it needs hashable instances.
Putting the descriptor in the wrong place
Descriptors only work as class attributes. Assigning one in __init__, as in self.price = Positive(), stores an ordinary object in the instance dictionary and none of its methods are called.
Forgetting `__set_name__` on older code paths
__set_name__ is only called when the class body creates the class. If you attach a descriptor afterward with Item.other = Positive(), Python does not call it. Call Item.other.__set_name__(Item, 'other') yourself in that case.
Ignoring `obj is None`
If __get__ assumes obj is an instance, then Item.price raises an AttributeError or a TypeError from inside your code. That also breaks introspection tools. Always handle the None case.
When to use a descriptor instead of a property
Use property when the logic belongs to one attribute of one class. Use a descriptor when the same logic repeats across several attributes or classes, such as validation, type checks, unit conversion or lazy loading. Descriptors cost more to read, so for a single attribute a property is the simpler choice.
Exercise
A descriptor class Name defines only _get and returns the string 'class value'. A class has label = Name(). After obj = Owner() and `obj.dict['label'] = 'instance value', what does obj.label` return, and what changes if you add a set_ method to Name that does nothing?
Show answer
Without _set, Name is a non-data descriptor, so the instance dictionary wins and obj.label returns 'instance value'. Once set_ is added, Name becomes a data descriptor, which takes priority over the instance dictionary, so obj.label returns 'class value'.
Exercise
Why does Positive store its value under '_' + name instead of under name itself?
Show answer
The data descriptor intercepts every assignment to the public name. Calling setattr(obj, 'price', value) from inside _set would trigger set_ again and recurse without end. A separate private name avoids that and keeps per-instance data on the instance.