How can I get the attribute name when working with descriptor protocol in Python? How can I get the attribute name when working with descriptor protocol in Python? python python

How can I get the attribute name when working with descriptor protocol in Python?


There is a simple way, and there is a hard way.

The simple way is to use Python 3.6 (or newer), and give your descriptor an additional object.__set_name__() method:

def __set_name__(self, owner, name):    self.name = '_' + name

When a class is created, Python automatically will call that method on any descriptors you set on the class, passing in the class object and the attribute name.

For earlier Python versions, the best next option is to use a metaclass; it'll be called for every subclass that is created, and given a handy dictionary mapping attribute name to attribute value (including you descriptor instances). You can then use this opportunity to pass that name to the descriptor:

class BaseModelMeta(type):    def __new__(mcls, name, bases, attrs):        cls = super(BaseModelMeta, mcls).__new__(mcls, name, bases, attrs)        for attr, obj in attrs.items():            if isinstance(obj, Field):                obj.__set_name__(cls, attr)        return cls

This calls the same __set_name__() method on the field, that Python 3.6 supports natively. Then use that as the metaclass for BaseModel:

class BaseModel(object, metaclass=BaseModelMeta):    # Python 3

or

class BaseModel(object):    __metaclass__ = BaseModelMeta    # Python 2

You could also use a class decorator to do the __set_name__ calls for any class you decorate it with, but that requires you to decorate every class. A metaclass is automatically propagated through the inheritance hierarchy instead.


I go through this in my book, Python Descriptors, though I haven't updated to a second edition to add the new feature in 3.6. Other than that, it's a fairly comprehensive guide on descriptors, taking 60 pages on just the one feature.

Anyway, a way to get the name without metaclasses is with this very simple function:

def name_of(descriptor, instance):    attributes = set()    for cls in type(instance).__mro__:        # add all attributes from the class into `attributes`        # you can remove the if statement in the comprehension if you don't want to filter out attributes whose names start with '__'        attributes |= {attr for attr in dir(cls) if not attr.startswith('__')}    for attr in attributes:        if type(instance).__dict__[attr] is descriptor:            return attr

Considering every time you use the name of the descriptor, the instance is involved, this shouldn't be too difficult to figure out how to use. You could also find a way to cache the name once you've looked it up the first time.