Search code examples
overridingpython-c-apisubtype

Python C API, How to call base type method from subtype?


I created a subtype from one existing Python type with C API by following this guide Python C API Defining New Types

I overridden one base type's method by registering the new method thanks to tp_methods attribute of the new PyTypeObject. This is working fine.

But, the code must also be able to execute the base type method (the one that has been overrided. I can not find documentation on how to do it.

Any idea are welcome, Thanks


Solution

  • I think there's 2.5 options, in order of complexity:

    1. Just find the C function that defines it. When using the C API the chances are you're inheriting from a known class that is implemented in C. In that case you'd track down the C function used for the method and call that.

    2. Get the class from the object, the base from the class:

      a. PyObject* baseclass = self->ob_type->tp_base;

      b. Use the C API equivalent of super():

      PyObject* baseclass = PyObject_CallFunctionObjArgs(&PySuper_Type,self->ob_type,self,NULL);

      With the base found you can then use the C API equivalent of getattr to get the relevant function:

    .

    /* check baseclass against null */
    PyObject* func = PyObject_GetAttrString(baseclass,"function_name");
    /* check func is not null */
    PyObject* result = PyObject_CallFunctionObjArgs(self,other_arguments..., NULL); /* adjust arguments here */
    Py_DECREF(func);
    // decref result?
    

    You can use a different method of calling it but you need to make sure you pass self with the arguments.


    Option 2b is probably most flexible since it should work when multiple bases are defined through the tp_bases.