CodeBlanks Logo Icon CodeBlanks

__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.

Practice 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.

Starter code

main.py
# Write the TrackedField descriptor
# use it in the Config class
# print the value

Sample solution

main.py
# 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)

Expected output

host tracked

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match __set_name__ concepts

Term Meaning
__set_name__ Name notification
owner Owning class
name Attribute name
automatic Python calls it

2 Complete the __set_name__ signature

Question
def __set_name__(self, owner, ____):
    self.name = name
Answer
def __set_name__(self, owner, name):
    self.name = name

Explanation: The name parameter carries the attribute name.

3 When is __set_name__ called?

main.py
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 Correct answer
  • Only when __get__ is called
  • When the program exits

Explanation: __set_name__ fires automatically the moment class Config is defined; no instance is needed.

All lessons in Expert