Part 14 / Topic 4 of 11
Descriptors
A descriptor is an object, stored as a class attribute, that controls what happens when that attribute is read or set on an instance. It is any object whose class has some of these methods:
| Method | Called when | Arguments |
|---|---|---|
__get__(self, obj, objtype) |
obj.attr is read |
the instance (None if read on the class) and its class |
__set__(self, obj, value) |
obj.attr = value |
the instance and the new value |
__set_name__(self, owner, name) |
the class is created | the class and the attribute's name |
Think of a security guard at a door: everyone going in or out of that one door is checked, and the same guard can be hired for many doors.
How @property works
property is a descriptor class. @property puts a property object in the class's __dict__. Reading circle.area makes Python call that object's __get__, which calls your method.
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return round(3.14159 * self.radius ** 2, 2)
wheel = Circle(2)
prop = Circle.__dict__["area"]
print(type(prop).__name__) # property
print(prop.__get__(wheel, Circle)) # 12.57 (what wheel.area does for you)
print(hasattr(prop, "__set__")) # True (that is why wheel.area = 5 fails)
A descriptor with __set__ is a data descriptor: it wins over the instance __dict__. One with only __get__ (like a plain function, which is how methods get self) is a non-data descriptor: the instance __dict__ wins.
A reusable validated field: PositiveNumber
With @property you write a getter and setter for every field. A descriptor class writes the check once and reuses it.
class PositiveNumber:
def __set_name__(self, owner, name):
self.name = name # "price", "stock", ...
self.private_name = "_" + name # where the value is really stored
def __get__(self, obj, objtype=None):
if obj is None: # read on the class: Product.price
return self
return getattr(obj, self.private_name)
def __set__(self, obj, value):
if not isinstance(value, (int, float)) or value <= 0:
raise ValueError(f"{self.name} must be positive, got {value!r}")
setattr(obj, self.private_name, value)
class Product:
price = PositiveNumber() # __set_name__ gets "price"
stock = PositiveNumber() # __set_name__ gets "stock"
def __init__(self, name, price, stock):
self.name = name
self.price = price # calls PositiveNumber.__set__
self.stock = stock
kettle = Product("Kettle", 1299, 15)
print(kettle.price, kettle.stock) # 1299 15
print(kettle.__dict__)
# {'name': 'Kettle', '_price': 1299, '_stock': 15}
try:
kettle.price = -50
except ValueError as error:
print(error) # price must be positive, got -50
The same PositiveNumber can guard a loan amount, a weight, a salary: any class, any field.
๐ Going deeper:
@staticmethod,@classmethod,functools.cached_propertyand dataclass fields all use the descriptor protocol. Django and SQLAlchemy model fields are descriptors too.
Full program: examples/03_attributes_and_descriptors.py.
Done here? The practice set for Part 14 โ 8 exercises with solutions โ is on the part page.