Sub topic 7
Writing a descriptor: __set_name__ and per-instance storage
This chapter assumes you know how to write Python classes, the difference between instance and class attributes, and the special methods __get__ and __set__. You should also know that a data descriptor beats an entry of the same name in the instance __dict__.
The problem: one descriptor, many instances
A descriptor object lives on the class. Every instance of that class shares the same descriptor object. If the descriptor stores a value on itself, all instances share that value.
class Broken:
def __init__(self):
self.value = None
def __get__(self, obj, objtype=None):
return self.value
def __set__(self, obj, value):
self.value = value # shared by every instance
class Box:
size = Broken()
a = Box()
b = Box()
a.size = 1
b.size = 2
print(a.size) # 2, not 1The descriptor has no per-instance state of its own. It has to keep each instance's value somewhere that belongs to that instance.
Storing the value on the instance
The usual place is the instance __dict__, under a private name. The descriptor also needs to know which attribute name it was assigned to, so it can build that private name.
Python tells it. When a class body finishes, type.__new__ calls __set_name__(owner, name) on every attribute that defines it. owner is the new class and name is the attribute name.
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(f"{self.private_name[1:]} 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, 3)
print(item.price) # 9.5
item.quantity = 0 # raises ValueErrorHere price and quantity are two separate Positive objects. Each got its own private_name from __set_name__: _price and _quantity. Each Item instance keeps its numbers in its own __dict__ under those names.
Why `__get__` returns `self` when `obj` is None
Accessing the attribute on the class, as in Item.price, calls __get__(None, Item). There is no instance to read from. Returning the descriptor itself lets tools and you inspect it. Without the check, getattr(None, "_price") raises a confusing AttributeError.
Why the private name is different
The descriptor is a data descriptor, so it wins over the instance __dict__ entry named price. If you stored the value under the public name with obj.__dict__["price"], it would also work, because __get__ would still run first and read it. Using setattr with the same public name would instead call __set__ again and recurse forever. A different private name avoids that trap and keeps the code simple.
Common mistakes
- Storing state on
selfinside the descriptor, which shares it across instances. - Forgetting
__set_name__, soprivate_nameis never set and__get__fails withAttributeError. - Assigning a descriptor after the class exists, for example
Item.extra = Positive(). Python does not call__set_name__then. Call it yourself:Item.extra.__set_name__(Item, "extra"). - Using
setattr(obj, self.name, ...)with the public name, which re-enters__set__.
Exercise
In the Positive descriptor, why does __set__ call setattr(obj, "_price", value) and not setattr(obj, "price", value)?
Show answer
price is a data descriptor on the class, so setattr(obj, "price", value) would call Positive.__set__ again, which would call setattr again, and so on until a RecursionError. The private name _price is not a descriptor, so it is stored directly in the instance __dict__.
Exercise
Two classes each define qty = Positive(). Does the private name _qty collide between them?
Show answer
No. Each class has its own Positive object with its own private_name, and each instance stores _qty in its own __dict__. Different instances never share the value.