Is it possible to call PyObject_CallMethod only once for a PySequence_Fast loop?

Viewed 147

I'm working on a python module implemented using the "C" API for Python 3.7. I'm trying to speed up a PySequence_Fast() loop that calls a function using PyObject_CallMethod(). Since the objects are all the same python class, I was hoping to avoid the overhead of resolving the function name each time. Is that possible?

Here's the (reduced) code fragment I'm trying to improve:

    PyObject *seq = PySequence_Fast(object_list,"not a sequence");
    int len = PySequence_Size(object_list);
    for ( int n = 0 ; n < len ; n++ )
    {
        PyObject *obj = PyList_GET_ITEM(seq,n);
        PyObject_CallMethod(obj,"my_function",NULL);
    }

Thanks in advance.

1 Answers

Just do the exact same thing you'd do in Python, but through the C API.

In Python, you'd be transforming

for thing in stuff:
    thing.method()

to

method = ThingClass.method
for thing in stuff:
    method(thing)

So do an attribute lookup on the class of your objects to find the unbound method, with PyObject_GetAttrString, and call it with PyObject_CallObject or PyObject_CallFunctionObjArgs or whatever means of calling things you decide is most convenient.

Related