Robert Steckroth, 23.11.2012 17:26:
> Hey Gang, I am using object attributes from other objects in my module. Can
> anyone tell me the best way to retrieve the object attributes without
> un-necessary overhead? Is it better to simply call
> a PyObject_GetAttrString(My_object, "width")?
You should read the source. It will create an intermediate Python object
for the attribute name.
> Does it create un-necessary overhead to declare the object in the head of
> the function as so? >
> My_object *m_obj;
> w = m_obj->width;
If the field you are accessing is a C field in an extension type, then yes,
that's the way to do it. This is a straight C pointer dereference that is
way more efficient than a dict lookup of a Python attribute and the packing
or unpacking of a Python object value that tends to go with it.
> Also, would I need to --> Py_XDECREF(m_obj) at the end of the function if
> this is a "clean" way of doing it?
Depends on where you got the value from. If you own the reference, you have
to decref it at the end, yes.
> Is there any performance concerns between the two?
Not unless your code is performance critical. If it is, you will prefer the
direct pointer dereference. Otherwise, you don't have to care.
In any case, you should first write your code, then benchmark it, then see
if it's fast enough or if it needs improvements and/or optimisation. C code
is not Python code. It's way harder to write and to get right. So a) avoid
writing it in the first place and b) if you find that you really have to,
write as little of it as possible and avoid premature optimisations on the way.
I keep repeating myself, but there are tools that take care of all of the
above for you automatically.
Stefan