Python
__set_name__
Learn name awareness with __set_name__.
What is __set_name__?
__set_name__(self, owner, name) is called automatically by Python when a descriptor is assigned as a class attribute. owner is the class and name is the attribute name.
This lets the descriptor know which name it was defined under. For example class Config: host = TrackedField() triggers TrackedField.__set_name__ with name="host". The descriptor can then use its own name in error messages or logging. This method was added in Python 3.6 and brings name awareness without a metaclass.
Using the name information
You can use the name from __set_name__ in several ways. The two most common are adding it to error messages and producing a transformed value in __get__.
For example you can store self.name = name and return f"{self.name} ready" in __get__. This lets the descriptor know which attribute it is bound to and makes debugging easier. You can also access the owning class through owner to register at class level.
Exercise Name tracking with __set_name__
Write a TrackedField descriptor. In __set_name__(self, owner, name) set self.name = name. __get__(self, obj, objtype=None) returns f"{self.name} tracked". In a Config class define host = TrackedField(). Create an instance and print host.
Show example solution
# Write the TrackedField descriptor
class TrackedField:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
return f"{self.name} tracked"
class Config:
host = TrackedField()
c = Config()
print(c.host)
Test yourself
-
Match __set_name__ concepts
- __set_name__
- Name notification
- owner
- Owning class
- name
- Attribute name
- automatic
- Python calls it
-
Complete the __set_name__ signature
def __set_name__(self, owner, ____):
self.name = name
Show answer
def __set_name__(self, owner, name):
self.name = name
-
When is __set_name__ called?
class TrackedField:
def __set_name__(self, o, n):
print(n)
class Config:
host = TrackedField()
- When an instance is created
- Automatically when the class is defined
- Only when __get__ is called
- When the program exits
Show answer
Automatically when the class is defined — __set_name__ fires automatically the moment class Config is defined; no instance is needed.
Next lesson: Summary - Descriptors