Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Python slots based object members in C

I have a Python class based on slots to save space

class my_class(object):

    __slots__ = ('x', 'y')

    def __init__(self, x, y):
        self.x = x
        self.y = y

I need to access objects of this class from a C function. When I print

obj->ob_type->tp_name

from C, I see my_class but can't find a way of accessing the member values on the instance.

like image 685
user2050283 Avatar asked Dec 05 '25 03:12

user2050283


1 Answers

For each name in __slots__, Python generates a descriptor object on the class (stored in the PyTypeObject.tp_members struct). Each descriptor stores an offset, just like the __dict__ attribute is stored as an offset.

If you already know the names of the slots and just want to access the values on each instance for those, just use the normal PyObject_GetAttrString() function to leave it to the C-API to access the slots for you.

like image 61
Martijn Pieters Avatar answered Dec 07 '25 16:12

Martijn Pieters