Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access attributes stored on Python descriptors?

Tags:

python

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.

like image 647
matthewatabet Avatar asked Oct 23 '25 14:10

matthewatabet


1 Answers

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.

like image 144
BrenBarn Avatar answered Oct 25 '25 02:10

BrenBarn