Let's say I have the following descriptor:
class MyDescriptor(object):
def __init__(self, name, type_):
self.name = name
self.type_ = type_
def __set__(self, obj, value):
assert isinstance(value, self.type_)
obj.__dict__[self.name] = value
Is there a way to access type_ from an object employing MyDescriptor?
i.e.
class MyObject(object):
x = MyDescriptor('x', int)
my_object = MyObject()
my_object.x = 5
print my_object.x.type_
As far as I'm aware, this will raise AttributeError as my_object.x is an int. But, I'm wondering if there's a good way to associate metadata with descriptors.
EDIT: adjusted wording to indicate that there's one instance of a descriptor per class.
Is there a way to access type_ from the object instance which owns the MyDescriptor instance?
There is no object instance which owns the MyDescriptor instance. There is one instance of MyDescriptor which is stored on the class of which the descriptor is an attribute (MyObject in your example). That's how descriptors work. You can access this descriptor instance via the class as described in user2357112's answer, but be aware that you're accessing class-level data. If you want to store instance-level data with the descriptor, you need to store it on the instance itself (i.e., on the object passed as obj to your __set__/__get__) rather than on the descriptor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With