3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user2050283
  • 562
  • 1
  • 4
  • 9
  • What kind of access are you looking for? Do you need to know the names of the slots (introspection) or do you know that there are `x` and `y` attributes and just need to access them? – Martijn Pieters Sep 01 '15 at 15:51
  • I know their names. Just need to access the values. – user2050283 Sep 01 '15 at 15:57
  • I was able to access them just now using PyObject_GetAttrString(obj, "x"). Is that the preferred method or is there a faster way? – user2050283 Sep 01 '15 at 15:58
  • That's the preferred method. They are just attributes, really, implemented as descriptors on the class, accessing the value in the instance memory space. – Martijn Pieters Sep 01 '15 at 16:03

1 Answers1

1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343