Sub topic 15
Descriptors: the mechanism behind property
This chapter assumes you can write properties with @property and setters, and that you know how __init__ and class attributes work. A descriptor is the general mechanism that property is built on. You rarely need to write one, but knowing how they work explains several behaviors you have already seen.
The descriptor protocol
A descriptor is an object stored as a class attribute that defines at least one of these methods:
__get__(self, obj, objtype=None)runs when the attribute is read.__set__(self, obj, value)runs when the attribute is assigned on an instance.__delete__(self, obj)runs when the attribute is deleted.
Python checks for these methods whenever it looks up an attribute. property is a built-in class that implements all three and forwards them to your getter, setter, and deleter functions.
class Demo:
@property
def x(self):
return 1
print(type(Demo.x)) # <class 'property'>
print(Demo.x.fget.__name__) # x
print(hasattr(Demo.x, "__get__"), hasattr(Demo.x, "__set__")) # True TrueA reusable descriptor
A property's validation lives inside one class. If three attributes need the same rule, you would write three nearly identical properties. A descriptor lets you write the rule once.
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(9.5, 2)
print(item.price) # 9.5
try:
item.quantity = 0
except ValueError as exc:
print(exc) # value must be positive__set_name__ is called when the class is created. It tells the descriptor which attribute name it was assigned to, so price is stored as _price and quantity as _quantity. When obj is None, the attribute was read from the class itself, and returning self lets Item.price give you the descriptor.
Lookup order
Descriptors that define __set__ or __delete__ are called data descriptors. Those with only __get__ are non-data descriptors. The difference controls which one wins when an instance's __dict__ holds the same name.
A property is a data descriptor, so the instance dictionary cannot shadow it:
class Demo:
@property
def x(self):
return 1
d = Demo()
d.__dict__["x"] = 99
print(d.x) # 1, the property still winsfunctools.cached_property is a non-data descriptor. On first access it computes the value and writes it into the instance's __dict__. Later reads find the instance value before reaching the descriptor, which is why the computation runs only once.
Ordinary functions are non-data descriptors too. Their __get__ is what turns obj.method into a bound method.
Common errors
- Storing the value on the descriptor. Writing
self.value = valueinside__set__stores one value on the shared descriptor object, so every instance sees it. Store it onobj, asPositivedoes. - Forgetting the
obj is Nonecase. Without it,Item.priceraisesAttributeErrorinstead of returning the descriptor, which breaks introspection tools. - Defining descriptors on instances. The protocol only works for attributes on the class. A descriptor assigned in
__init__asself.price = Positive()is just a plain object.
Exercise
A class defines x as a property with a getter only, and you run obj.__dict__["x"] = 5 and then read obj.x. What do you get, and why?
Show answer
The getter's result, not 5. A property is a data descriptor (it defines __set__, which raises AttributeError when there is no setter), and data descriptors take priority over the instance __dict__ during lookup.