Sub topic 15
Descriptors: the mechanism behind property
What this chapter assumes
You should already be comfortable with the following:
- Writing
@propertygetters and setters. - Instance attributes stored in
self.__dict__. - The single-underscore convention for internal names.
- Raising exceptions.
This chapter explains what property is made of. It shows how to write the same machinery yourself, and why you would.
The descriptor protocol
A descriptor is an object, stored as an attribute of a class, that defines at least one of these methods:
| Method | Called when | Typical job |
|---|---|---|
| `__get__(self, obj, objtype=None)` | The attribute is read | Return the value |
| `__set__(self, obj, value)` | The attribute is assigned on an instance | Validate and store |
| `__delete__(self, obj)` | `del` is used on the attribute | Remove the value |
| `__set_name__(self, owner, name)` | The class body finishes executing | Learn the attribute name |
Python calls these methods automatically. You never call __get__ yourself in normal code. The descriptor must live on the class, not on an instance. A descriptor assigned to self.something in __init__ is an ordinary object and is never invoked.
In __get__, obj is the instance, or None when the attribute is read from the class itself (Item.price). objtype is the class.
A reusable validator
The property approach repeats the same validation code for every attribute. 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 positiveFollow what happens step by step:
- When the
Itemclass body finishes, Python callsPositive.__set_name__once per descriptor. The first call receives"price"and the second receives"quantity". Each descriptor now knows where to keep its data:_priceand_quantity. - In
__init__,self.price = pricefinds thePositiveobject on the class and calls its__set__. Validation therefore runs from construction onward, as with the setter pattern from earlier chapters. item.pricecalls__get__, which reads_pricefrom the instance.
The obj is None check lets Item.price return the descriptor itself. Tools such as help() and documentation generators rely on this behavior.
Keep per-instance data on the instance
The most common descriptor bug is storing the value on the descriptor. There is only one descriptor object per class attribute, so every instance would share it:
class BadPositive:
def __get__(self, obj, objtype=None):
if obj is None:
return self
return self.value
def __set__(self, obj, value):
if value <= 0:
raise ValueError("value must be positive")
self.value = value # shared by every instance
class Item:
price = BadPositive()
a = Item()
b = Item()
a.price = 1
b.price = 2
print(a.price) # 2, not 1Store data in obj (as Positive does with setattr), or in a WeakKeyDictionary keyed by instance if the instances cannot hold new attributes.
A second bug is using the public name for storage. If Positive called setattr(obj, "price", value), the assignment would trigger __set__ again and recurse forever. The underscore prefix avoids this. The alternative is to write directly into obj.__dict__[name].
How attribute lookup finds a descriptor
Descriptors work because of the order in which Python searches for an attribute on an instance. Descriptors that define __set__ or __delete__ (data descriptors) take priority over the instance dictionary. Descriptors with only __get__ (non-data descriptors) lose to it.
Assignment is simpler. obj.name = value calls __set__ if the class has a data descriptor for name. Otherwise it writes into the instance dictionary.
The difference shows up in a short experiment:
class Loud:
def __get__(self, obj, objtype=None):
return "from descriptor"
class A:
x = Loud()
a = A()
print(a.x) # from descriptor
a.x = "mine" # no __set__, so this goes to a.__dict__
print(a.x) # mine
print(A.x) # from descriptorAdd a __set__ method to Loud and the second print would no longer show mine. The descriptor would intercept the assignment and win every read.
This rule explains two things you have already used:
- Functions are non-data descriptors. Their
__get__turnsobj.methodinto a bound method. functools.cached_propertyis a non-data descriptor. On first access it computes the value and stores it in the instance dictionary under the same name. Later reads find the dictionary entry first, so__get__is never called again. A data descriptor would block this trick, socached_propertydeliberately defines no__set__.
property is a descriptor
property is a data descriptor implemented in C. Its behavior is the same as this pure-Python version:
class MyProperty:
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
self.__doc__ = doc if doc is not None else getattr(fget, "__doc__", None)
self.name = getattr(fget, "__name__", "attribute")
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError(f"property {self.name!r} has no getter")
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError(f"property {self.name!r} has no setter")
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError(f"property {self.name!r} has no deleter")
self.fdel(obj)
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return type(self)(self.fget, self.fset, fdel, self.__doc__)
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@MyProperty
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("temperature is below absolute zero")
self._celsius = value
t = Temperature(20)
print(t.celsius) # 20
try:
t.celsius = -500
except ValueError as exc:
print(exc) # temperature is below absolute zeroThree details connect this code to what you know about property:
@celsius.setterdoes not modify the existing object. It returns a new one with the setter filled in, and the decorator assigns that to the same class attribute name.- A property with no setter still defines
__set__. That is why assignment raisesAttributeErrorinstead of quietly writing to the instance dictionary. A property is always a data descriptor, which is also why it overrides any same-named entry in__dict__. - The
property(fget, fset, fdel, doc)form from the previous chapter builds the same object. The decorator syntax only changes how you write the call.
Choosing between a property and a descriptor class
| Situation | Use |
|---|---|
| One attribute with its own rule | `@property` |
| Computed from other attributes, nothing stored | `@property` |
| Expensive, computed once per instance | `cached_property` |
| Same rule applied to several attributes or classes | Descriptor class |
| You need the attribute name or owner class inside the logic | Descriptor with `__set_name__` |
Descriptors add indirection. A reader who sees price = Positive() must find the class to learn what assignment does. Use one when repetition is a real cost. If a rule appears once, a property is easier to read.
Gotchas
- Instance-level descriptors do nothing.
self.price = Positive()in__init__stores an object. Python only runs the protocol for descriptors found on the class. __slots__and__dict__. A descriptor that stores data withsetattrneeds somewhere to put it. With__slots__, declare the private slot names, or the assignment fails.- Subclass overrides. A descriptor is inherited like any class attribute. A subclass can replace it, but the replacement must be another descriptor if you want the same interception.
- Name reuse. Assigning one descriptor object to two names in the same class gives both names the
private_nameof whichever__set_name__call ran last. Create a separate instance per attribute, asItemdoes.
Exercise
A class defines limit = Positive() using the descriptor above. A colleague changes Positive.__set__ so that it stores the value in self.value instead of calling setattr(obj, self.private_name, value). Two Item objects now report the same limit. Why?
Show answer
The Positive object is created once, when the class body runs, and every instance of the class shares it. Storing the value on self inside __set__ writes to that single shared object, so the last assignment overwrites the value for every instance. The value must be stored on obj, or in a per-instance structure such as a WeakKeyDictionary keyed by obj.
Exercise
A class has a descriptor d that defines only __get__. An instance runs obj.d = 5, and obj.d is then read. What does the read return? What changes if the descriptor also defines __set__?
Show answer
With only __get__ (a non-data descriptor), the assignment writes 5 into the instance dictionary, and the read returns 5 because the instance dictionary beats a non-data descriptor. If __set__ is added (a data descriptor), the assignment calls __set__, and the read calls the descriptor's __get__, which beats the instance dictionary.