Sub topic 6
Letting descriptors learn their names with __set_name__
This chapter assumes you know how descriptors work (__get__ and __set__), how a class statement defines attributes, and the basics of super(). You don't need metaclasses yet.
The problem: a descriptor does not know its name
A descriptor is an object stored as a class attribute. Take this line:
price = Positive()The Positive() call runs before the assignment. The object it creates has no idea that it will end up under the name price. A reusable validating descriptor still needs that name, for error messages and to decide where to keep each instance's value.
Before Python 3.6 you had two options: pass the name by hand (price = Positive('price')) or write a metaclass that scanned the namespace. Both were error-prone. __set_name__ removes the need for either.
How __set_name__ works
When Python finishes creating a class object, it looks through the class namespace. For every value whose type defines __set_name__, it calls:
value.__set_name__(owner, name)owner is the new class and name is the attribute name the value was assigned to. This happens once per attribute, in definition order, before any instance exists. Python calls it as part of type.__new__, so a metaclass that calls super().__new__ gets this behavior for free.
A reusable validated field
This descriptor stores each value in the instance __dict__ under the attribute's own name. A data descriptor (one that defines __set__) takes priority over the instance dictionary, so __get__ still runs on every read.
class Positive:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
try:
return obj.__dict__[self.name]
except KeyError:
raise AttributeError(self.name) from None
def __set__(self, obj, value):
if value <= 0:
raise ValueError(f'{self.name} must be positive, got {value!r}')
obj.__dict__[self.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, item.quantity) # 9.5 3
print(Item.price.name) # price
try:
item.quantity = 0
except ValueError as exc:
print(exc) # quantity must be positive, got 0The error message names quantity without any name being passed in. The class Item never mentions the strings 'price' or 'quantity' for the descriptor to use.
The tutorial's earlier example stored values under a private name like _email. Either choice works. Storing under the public name keeps vars(item) readable, but the descriptor must be a data descriptor, or the instance dictionary would shadow it.
Common errors
- Adding a descriptor after the class exists.
__set_name__runs only during class creation. AssigningItem.discount = Positive()later does not call it, soself.nameis never set and the first access raisesAttributeError. Call it yourself:Item.discount.__set_name__(Item, 'discount'). - Sharing one descriptor under two names. Python calls
__set_name__once for each name, and the last call wins. Withshared = Positive()followed bya = sharedandb = sharedin a class body,shared.nameends up as'b'. Both attributes then read and write the key'b'. Create a separate descriptor per attribute. - Forgetting
obj is None. AccessingItem.priceon the class passesNoneasobj. Returnselfso that introspection works, as the example does. - Failures inside
__set_name__. Since 3.12, an exception raised inside the hook propagates with a note naming the attribute. Older versions wrapped it in aRuntimeError. Keep the hook simple, and have it only record names.
Descriptors that delegate to a wrapped object, such as functools.cached_property, use the same hook.
Why this helps later
__set_name__ handles the common job of "this attribute needs to know its own name". The later chapters on class decorators and metaclasses cover jobs that need to see the whole class at once, which this hook cannot do.
Exercise
A class body contains shared = Positive(), then a = shared, then b = shared, using the Positive descriptor from this chapter. After the class is created, what is Cls.shared.name, and what happens when you set obj.a = 5 and then read obj.b?
Show answer
__set_name__ is called for each of the three names in order (shared, a, b), so the last call leaves name as 'b'. Setting obj.a = 5 stores the value in obj.__dict__['b'], so reading obj.b returns 5. Both attributes share one slot. The fix is to create a separate Positive() for each attribute.