CPython, inheritance from Python binaries to C binaries

I’m trying to create a custom type in CPython that inherits from an already defined type object in Python. My approach thus far is to use PyImport_ImportModule , then access the PyTypeObject and set it to the tp_base attribute in my PyTypeObject .

The following is an incredibly hacky attempt to do so.


PyTypeObject typeObj = {...} // Previously defined PyTypeObject for a fallback

int init() {
    PyObject* obj = PyImport_ImportModule("<absolute_path_to_python_module>");
    if (obj && PyObject_HasString(obj, "<python_type_object>")) {
        PyTypeObject* type_ptr = (PyTypeObject*) PyObject_GetAttrString(obj, "<python_type_object>");
        typeObj = *type_ptr;
    if (PyType_Ready(&typeObj) < 0) return -1;
    ... // Other initialization stuff


PyTypeObject CustomType = {
    ... // Initialization stuff
    .tp_base = &typeObj;

The custom type is able to inherit the functions, but fails on isInstance(CustomType(), TypeObj) . When I try to access the __bases__ attribute of the custom type, it raises a segmentation fault.

Your basically copying the C struct for the imported type, and it doesn’t surprise me that this crashes the interpreter.

What you should do is use “type_ptr” instead of “typeObj”.

Thank you! That seemed to solve the initial problem.