In this lesson, you will learn how to use the __set_name__ hook to automatically detect the name of the class attribute your descriptor is assigned to, eliminating the need for manual, error-prone naming.
The Problem with Manual Naming
When you implement a descriptor, you often need to store the value in the instance's __dict__ using a specific key. Traditionally, you might pass the attribute name as a string when initializing the descriptor:
class Validator:
def __init__(self, name):
self.name = name
def __set__(self, instance, value):
instance.__dict__[self.name] = value
class User:
# Redundant: 'username' is typed twice!
username = Validator('username')
This approach is repetitive and brittle. If you rename the class attribute but forget to update the string passed to the constructor, your code will break.
Automating with __set_name__
Introduced in Python 3.6, the __set_name__(self, owner, name) method is called automatically by the interpreter when the class is created. The owner argument is the class where the descriptor is defined, and name is the actual variable name assigned to the descriptor.
By using this hook, we can capture the name dynamically:
class Validator:
def __set_name__(self, owner, name):
# Automatically captured at class creation
self.name = name
def __set__(self, instance, value):
instance.__dict__[self.name] = value
class User:
# No more redundant strings
username = Validator()
email = Validator()
When Python processes the User class, it sees the Validator instance assigned to username. It immediately calls __set_name__ on that descriptor, passing "username" as the name argument. This ensures your descriptor always knows its own name relative to the host class without you ever having to specify it manually. This pattern makes your descriptors cleaner, more reusable, and much safer to refactor.
Key Takeaway: The __set_name__ hook allows descriptors to self-register their assigned attribute name, removing the need for redundant naming and preventing synchronization bugs during refactoring.