Search⌘ K
AI Features

Set Name Method of the Descriptor Protocol

Understand how to use the __set_name__ method in Python descriptors to automatically capture attribute names assigned to them. Explore improvements in writing reusable, maintainable code by avoiding redundant naming and simplifying descriptor usage in your classes.

Signature of the __set_name__ method

This is a relatively new method that was added in Python 3.6, and it has this structure:

__set_name__(self, owner, name)

When we create the descriptor object in the class that is going to use it, we generally need the descriptor to know the name of the attribute it is going to be handling. This attribute name is the one we use to read from and write to __dict__ in the __ get__ and __set__ methods, respectively.

Example of the __set_name__ method

Before ...