Accessing __slots__ from C
pavlovevidence at gmail.com
Thu Sep 11 23:13:37 CEST 2008
On Sep 10, 7:41 am, Chris <ceb... at users.sourceforge.net> wrote:
> I'd like to be able to access an attribute of a particular Python
> object as fast as possible from some C code.
> I wondered if using __slots__ to store the attribute would allow me to
> do this in a faster way.
> The reason I'd like to do this is because I need to access the
> attribute inside a loop within some C code, and I find that the
> attribute lookup using the 'PyObject_GetAttrString' call is far slower
> than any of the subsequent calculations I perform in C.
> Using the 'PyObject_GetAttrString' function to get the attribute, I
> find it is slightly faster when the attribute is a slot than when it
> isn't, but that the attribute lookup remains the performance-limiting
You can determine the offset the of the slot in the object structure
querying the member descriptor of the type object.
descr = GetAttrString(cls,"varname");
offset = descr->d_member->offset;
slotvar = (PyObject*)(((char*)obj)+offset)
There might be some macros to simplify this.
Use at your own risk.
More information about the Python-list