Sub topic 16
Descriptors: reusable attribute behavior
This chapter assumes you know classes, instance attributes, and @property. A descriptor is an object that controls what happens when you read, assign, or delete an attribute on another class. You write the rule once and reuse it on many attributes.
The descriptor protocol
A descriptor is any object whose class defines one or more of these methods:
__get__(self, obj, objtype=None)runs when the attribute is read.__set__(self, obj, value)runs when the attribute is assigned.__delete__(self, obj)runs when the attribute is deleted.__set_name__(self, owner, name)runs once when the owning class is created. It tells the descriptor which attribute name it was assigned to.
The descriptor must be a class attribute of the owner. Python only looks for these methods on attributes found on the type, not on the instance.
A reusable validator
@property validates one attribute on one class. A descriptor does the same job for any attribute on any class.
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()
quantity = Positive()
def __init__(self, price, quantity):
self.price = price
self.quantity = quantity
item = Item(10, 3)
print(item.price, item.quantity) # 10 3
try:
item.quantity = 0
except ValueError as e:
print(e) # value must be positive
print(Item.price) # the Positive object itself__set_name__ gives each use its own storage name: _price and _quantity. When you access the attribute on the class (Item.price), obj is None, and returning self lets you inspect the descriptor.
Which rule wins
Python's attribute lookup checks for descriptors on the type before it checks the instance.
A data descriptor defines __set__ or __delete__. It takes priority over the instance dictionary. A non-data descriptor defines only __get__, so an instance attribute with the same name hides it. Functions are non-data descriptors. Their __get__ is what binds self when you call a method.
When to use one
Use a plain @property when one class needs custom behavior for one attribute. Use a descriptor when the same rule, such as validation, type checks, or lazy computation, applies to many attributes or classes.
Exercise
In the Positive descriptor, why does _set store the value with setattr(obj, self.privatename, value) instead of assigning self.value = value?
Show answer
The descriptor object is a class attribute, so every instance of the owner class shares it. Assigning self.value would make all instances share one value. Storing the value on obj, under a name made in _setname__, keeps the data separate for each instance and for each attribute.