Sub topic 7
Writing a Descriptor: __set_name__ and Per-Instance Storage
What this chapter assumes
You should already know the descriptor protocol (__get__, __set__, __delete__). You should also know that a data descriptor, one that defines __set__ or __delete__, beats the instance __dict__ during lookup. This chapter covers the practical question of where a descriptor keeps its values and how it learns its own attribute name.
The problem: one descriptor, many instances
A descriptor object is created once, when the class body runs. It is stored in the class namespace and shared by every instance. Any state you put on self inside a descriptor method is therefore shared by all instances.
class Naive:
def __init__(self):
self.value = None
def __get__(self, obj, objtype=None):
return self.value
def __set__(self, obj, value):
self.value = value
class Box:
size = Naive()
a = Box()
b = Box()
a.size = 1
b.size = 2
print(a.size) # 2, not 1Both boxes read and write the same Naive object, so the second assignment overwrites the first. A descriptor must keep per-instance data somewhere that depends on obj.
Learning the attribute name with __set_name__
A descriptor that stores data on the instance needs a key. Before Python 3.6 you had to pass the name by hand, as in price = Positive("price"), which invited typos and mismatches.
Now type.__new__ handles it. After it builds the class object, it looks through the class namespace. For each value whose type defines __set_name__, it calls value.__set_name__(owner, name). Here owner is the new class and name is the key the value was stored under.
A complete validating descriptor
This descriptor records its private name in __set_name__ and stores each instance's value under that name on the instance itself.
class Positive:
def __set_name__(self, owner, name):
self.public_name = 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.public_name} 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
first = Item(9.5, 3)
second = Item(1.0, 7)
print(first.price, second.price) # 9.5 1.0
print(vars(first)) # {'_price': 9.5, '_quantity': 3}
try:
first.quantity = 0
except ValueError as exc:
print(exc) # quantity must be positiveFour details matter here.
- The
obj is Nonebranch. AccessingItem.priceon the class calls__get__(None, Item). Returningselflets you inspect the descriptor. Without this branch, the class-level access would trygetattr(None, "_price")and raise an unhelpful error. - No infinite recursion. The descriptor stores under
_price, notprice. If__set__ransetattr(obj, "price", value), that call would find the same data descriptor and call__set__again, forever. - The assignment in
__init__is validated.self.price = pricegoes throughtype(self).__getattribute__'s sibling,__setattr__, which finds the data descriptor on the class and calls its__set__. Constructor arguments get the same checks as later assignments. - The first read after construction works.
__init__always writes the private attribute before any read happens. Reading an attribute that was never set raisesAttributeError: 'Item' object has no attribute '_price'. The message names the private attribute, notprice.
Choosing where to store the value
Three storage strategies are common.
| Strategy | How it works | Main drawback |
|---|---|---|
| Private attribute | `setattr(obj, "_" + name, value)` | Exposes `_price` as a second, unvalidated way to write |
| Instance `__dict__` under the public name | `obj.__dict__[name] = value` | Fails for classes without `__dict__`, such as those using only `__slots__` |
| `WeakKeyDictionary` on the descriptor | `self.data[obj] = value` | Instances must be hashable and weak-referenceable |
Storing in obj.__dict__ under the public name works because the descriptor is a data descriptor. The lookup rules from the previous chapter guarantee the descriptor runs first, even though the instance dict has an entry with the same key.
class Typed:
def __init__(self, expected_type):
self.expected_type = expected_type
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 not isinstance(value, self.expected_type):
raise TypeError(f"{self.name} expects {self.expected_type.__name__}")
obj.__dict__[self.name] = value
class User:
age = Typed(int)
u = User()
u.age = 30
print(u.age, vars(u)) # 30 {'age': 30}
try:
u.age = "thirty"
except TypeError as exc:
print(exc) # age expects intHere vars(u) shows the clean public name, and __get__ converts a missing key into AttributeError. That conversion matters because a KeyError escaping from __get__ would not be treated as a missing attribute, so getattr(u, "age", None) and hasattr would raise instead of returning the default. Raising AttributeError from __get__ also triggers the __getattr__ fallback if the class defines one.
The WeakKeyDictionary approach keeps instances free of extra attributes, but it uses the instance as a key. That requires __hash__, and by default it compares by equality. A class that defines __eq__ without __hash__ is unhashable and cannot be used. Two equal instances with a custom __hash__ would also share one slot.
Edge cases with __set_name__
It runs only at class creation. If you attach a descriptor afterward, nothing calls __set_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):
setattr(obj, self.private_name, value)
class Late:
pass
Late.size = Positive()
try:
Late().size = 5
except AttributeError as exc:
print(exc) # 'Positive' object has no attribute 'private_name'
Late.size.__set_name__(Late, "size")
late = Late()
late.size = 5
print(late.size) # 5Calling __set_name__ yourself after assignment fixes it, but it is better to define descriptors in the class body.
One object under two names. If the same descriptor object appears under two names, __set_name__ runs once per name, and the last call wins. Both attributes then share one storage key.
Errors inside __set_name__. Python 3.12 and later let an exception from __set_name__ propagate unchanged, with a note naming the attribute. Earlier versions wrapped it in RuntimeError.
Subclasses. __set_name__ is called for descriptors defined in the class body being created, not again for inherited ones. A subclass shares the parent's descriptor object and its already-computed names.
A design check
Before you write a descriptor, ask whether you need one. If the validation applies to a single attribute on a single class, a property is shorter. A descriptor pays off when the same behavior repeats across several attributes or classes, as it does with price and quantity above.
Exercise
Given a Positive descriptor that records self.private_name = "_" + name in __set_name__, what does this print, and why?
class Shared:
x = y = Positive()
s = Shared()
s.x = 1
s.y = 2
print(s.x)
Show answer
It prints 2. The single Positive object is stored under both "x" and "y", so __set_name__ is called twice. The second call, with "y", overwrites private_name with "y". Both s.x = 1 and s.y = 2 therefore write to `y, and reading s.x returns the last value written. The fix is to create two separate descriptors: x = Positive() and y = Positive()`.