Thanks Serhiy. This does come with a performance penalty (in particular for function taking keyword arguments) but this is to be expected. Also the PyList_Insert solution does not sadly work for all the methods that I need to wrap.
Best Matthieu > On Aug 30, 2018, at 11:09 AM, Serhiy Storchaka <storch...@gmail.com> wrote: > > 29.08.18 17:33, Matthieu Dartiailh пише: >> I tried to look at the public C API for a way to call an unbound method with >> a minimal cost (in term of speed and memory). It seems to me, but please >> correct me if I am wrong, that one cannot call a MethodDef using only the >> public API. To use the public C API, one has to use PyCFunction_Call (or a >> variant) that expect a PyCFunctionObject which binds a the MethodDef to an >> instance. In my case, to avoid creating a temporary PyCFunctionObject each >> time I call list.insert on my custom subclass instance, I have to store that >> PyCFunctionObject for each instance. But this means storing 7 >> PyCFunctionObject per instance (one for each method of list I need to wrap). >> So I can either use the public API and increase the memory footprint or slow >> down the code by creating PyCFunctionObject for each call >> , or use large amount of the private API. >> Am I missing something ? > > In general, you need to cache the unbound method object, and call it with > self as the first argument. > > list_insert = PyObject_GetAttrString((PyObject *)&PyList_Type, "insert"); > ... > res = PyObject_CallFunctionObjArgs(list_insert, self, index, value, NULL); > > But in the particular case of the insert method it will be easier and more > efficient to use PyList_Insert(). > > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list