This question probably has an answer somewhere, but I couldn't find it.
I'm using setattr
to add a long list of descriptors to a class, and I have discovered that __set_name__
of the descriptor is not called when I use setattr
.
It is not a big issue for me because I can just set the name of the descriptor through __init__
instead, I just want to understand why __set_name__
is not called and if it's because I'm doing something wrong.
class MyDescriptor:
def __set_name__(self, owner, name):
self._owner = owner
self._name = name
def __get__(self, instance, owner):
return self._name
class MyClass:
a = MyDescriptor()
setattr(MyClass, 'b', MyDescriptor()) # dynamically adding descriptor, __set_name__ is not called!
mc = MyClass()
print(mc.a) # prints 'a'
print(mc.b) # raises AttributeError: 'MyDescriptor' object has no attribute '_name'
Since the update logic is in type.__new__(), notifications only take place at the time of class creation. If descriptors are added to the class afterwards, __set_name__() will need to be called manually
– Entrance