Sub topic 6
Letting descriptors learn their names with __set_name__
This chapter assumes you know how to define classes and call super(). It also assumes you have seen the descriptor protocol (__get__, __set__) at least once. The earlier chapters covered what a class statement does and how __init_subclass__ hooks into subclass creation. Here you will see how a descriptor finds out which attribute name it was assigned to.
The problem: a descriptor does not know its own name
A descriptor is an object with __get__, __set__ or __delete__ that lives as an attribute of a class. In a class body, the line email = Field() first builds a Field object and then binds it to the name email. The constructor call runs before the binding. The Field object therefore cannot see the name it is about to receive.
Before Python 3.6, the usual workaround was to make the programmer repeat the name:
class OldField:
def __init__(self, name):
self.name = name
class User:
email = OldField('email') # the name is written twice
age = OldField('emial') # a typo that nothing catchesThe duplication invites typos like the one above. The alternative was a metaclass or class decorator that scanned the namespace and patched each descriptor. Both are heavier than the problem requires.
The __set_name__ protocol
Python 3.6 added a hook for this. After a class object is created, Python looks at every value in the class namespace. If a value's type defines __set_name__, Python calls it:
descriptor.__set_name__(owner, name)owneris the class that was just created.nameis the attribute name the object was assigned to in the class body.
The hook is looked up on the type of the value, like other special methods. It does not have to be a descriptor, so any object placed in a class body can use it. Descriptors are the main use.
Here is the example from the plan. The Field descriptor derives its storage name from the attribute name:
class Field:
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 User:
email = Field()
u = User()
u.email = '[email protected]'
print(u._email) # [email protected]Python calls Field.__set_name__(User, 'email') once, right after User is created. The descriptor stores '_email' and uses it on every access. No name was typed twice.
The if obj is None: return self branch handles access through the class, as in User.email. Without it, getattr(None, ...) would fail. Returning the descriptor itself is the common convention, and it lets you inspect a field with User.email.
When the hook runs
The call happens inside type.__new__, after the class object exists and before type.__new__ returns. The order inside class creation is:
- Python runs the class body and collects the namespace.
type.__new__creates the class object.type.__new__calls__set_name__on each namespace value that defines it, in namespace order.type.__new__calls__init_subclass__on the parent.- Any class decorator runs afterwards, on the finished class.
You can check the order directly:
class Probe:
def __set_name__(self, owner, name):
print('1 __set_name__', name)
class Base:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print('2 __init_subclass__', cls.__name__)
class Child(Base):
p = Probe()This prints 1 __set_name__ p and then 2 __init_subclass__ Child. Because of this order, __init_subclass__ can rely on every descriptor already knowing its name. A parent class can loop over cls.__dict__ and use descriptor.name without checking whether naming has happened.
A worked example: a validating descriptor
A reusable validator is the typical real use. The descriptor below needs its name for two things: error messages, and storage in the instance.
class Validated:
def __init__(self, check, message):
self.check = check
self.message = message
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(
f'{type(obj).__name__!r} object has no value for {self.name!r}'
) from None
def __set__(self, obj, value):
if not self.check(value):
raise ValueError(f'{self.name}: {self.message} (got {value!r})')
obj.__dict__[self.name] = value
class Product:
title = Validated(lambda v: isinstance(v, str) and v, 'must be a non-empty string')
price = Validated(lambda v: isinstance(v, (int, float)) and v >= 0,
'must be a non-negative number')
def __init__(self, title, price):
self.title = title
self.price = price
p = Product('Pen', 2.5)
print(p.price) # 2.5
try:
p.price = -1
except ValueError as exc:
print(exc) # price: must be a non-negative number (got -1)This version stores the value in the instance __dict__ under the public name, not under '_price'. That works because Validated defines __set__, which makes it a data descriptor. Data descriptors on the class take priority over the instance dictionary, so p.price still goes through __get__. A descriptor with only __get__ would be shadowed by the instance entry, and the lookup would skip the descriptor.
Storing under the public name has one further benefit: vars(p) shows {'title': 'Pen', 'price': 2.5}, which is easier to debug than underscore-prefixed names.
The descriptor object itself is shared by every Product instance. This is why the value must live on obj, not on self. Storing the value on the descriptor would make all instances share one value.
Using the owner argument
The owner argument lets a descriptor register itself with its class. This example records the order of columns:
class Column:
def __set_name__(self, owner, name):
self.name = name
owner._columns = (*owner.__dict__.get('_columns', ()), name)
class Table:
id = Column()
title = Column()
print(Table._columns) # ('id', 'title')Reading owner.__dict__ rather than owner._columns matters. A plain owner._columns lookup would also find a parent's tuple through inheritance, and the example would then mix parent and child columns without any decision on your part. Whether you want that merging is a design choice, so make it explicitly. Python iterates over a copy of the namespace when it calls __set_name__, so setting attributes on owner inside the hook is safe.
Edge cases and common errors
Attributes added later are not named
The hook runs only during class creation. Assigning a descriptor to an existing class does nothing:
class Named:
def __set_name__(self, owner, name):
print(f'bound {name} on {owner.__name__}')
class A:
x = Named() # bound x on A
A.y = Named() # prints nothing
A.y.__set_name__(A, 'y') # bound y on AThe second line leaves A.y without a name, and any later use that reads self.name raises AttributeError. If you add descriptors dynamically, call __set_name__ yourself, as the last line does.
One descriptor, two names
If the same instance is assigned to two names, Python calls the hook twice, once per name, on the same object:
shared = Named()
class B:
a = shared
b = sharedThis prints bound a on B and then bound b on B. The second call overwrites any stored name, so a and b now share state keyed under 'b'. Create a separate descriptor instance per attribute, or have the hook raise an error if the name is already set.
Subclasses do not trigger it again
__set_name__ runs for the class whose body contains the descriptor. A subclass that inherits the attribute does not trigger another call. With class C(A): pass and the A above, nothing is printed. The name stored on the descriptor stays as it was assigned in A.
Errors inside the hook
If __set_name__ raises, class creation fails. Before Python 3.12, the exception was wrapped in a RuntimeError that said the error occurred while calling __set_name__. From 3.12 the original exception propagates with a note naming the attribute and the class. Either way, the class is not created, so validate arguments carefully.
Conflicts with __slots__
If a class defines __slots__, a slot name and a class attribute with the same name cannot coexist. A descriptor that computes '_' + name as its storage name needs '_email' listed in __slots__, or setattr will fail with AttributeError. Storing into obj.__dict__, as Validated does, does not work for slotted classes at all, because they have no instance dictionary.
Summary of when the hook is called
| Situation | Is `__set_name__` called? |
|---|---|
| Descriptor assigned in a class body | Yes, once per name, during class creation |
| Same instance assigned to two names | Yes, twice, with each name |
| `Cls.attr = Descriptor()` after creation | No |
| Subclass inherits the attribute | No |
| Created with `type(name, bases, ns)` | Yes, because `type.__new__` does the work |
The last row follows from the earlier chapter on type(). The hook belongs to class creation itself, and a class statement is only one way to trigger it.
Practice
Exercise
What does this code print, and why? class Named: def _setname__(self, owner, name): print('bound', name) class A: x = Named() class B(A): y = Named() A.z = Named()
Show answer
It prints "bound x" and then "bound y". Class A's creation names x. Class B's creation names y, but B does not rename the inherited x. The assignment A.z = Named() happens after A exists, so _setname_ is never called for z. To name it you must call A.z.setname__(A, 'z') yourself.
Exercise
A descriptor stores its value with setattr(obj, '_' + name, value). Two attributes in one class, a and b, are assigned the same descriptor instance. What goes wrong, and how can the descriptor guard against it?
Show answer
Python calls _setname_ twice on the same object, so the stored private name ends up as 'b'. Reads and writes through either a or b then use the single attribute 'b', so the two attributes share one value. The descriptor can guard against this by checking in setname__ whether it already has a name and raising an error if it does. The simpler fix is to create a separate instance for each attribute.