Python › Metaclasses & Class Customization

How does __set_name__ let a descriptor discover the attribute name it's assigned to within a class?

Intermediate

Answer

__set_name__(self, owner, name) is automatically called on a descriptor instance by the class creation machinery (part of type.__new__), passing the owning class and the attribute name it was assigned to in the class body. This lets descriptors avoid requiring the name to be passed explicitly and manually kept in sync, reducing a common source of bugs.
class Field:
    def __set_name__(self, owner, name):
        self.name = f'_{name}'
    def __get__(self, obj, objtype=None):
        return getattr(obj, self.name, None)
    def __set__(self, obj, value):
        setattr(obj, self.name, value)

class Model:
    title = Field()  # __set_name__ called automatically with name='title'
Real-world example A validation library's Field descriptor uses __set_name__ to automatically derive its private storage attribute name from the public attribute name, eliminating a common copy-paste bug of mismatched names.

Common follow-ups: When was __set_name__ introduced and what problem did it solve (PEP 487)?;How does this interact with __init_subclass__?