Skip to content

Support metaclass parameter in HPyType_FromSpec #296

@steve-s

Description

@steve-s

This necessary for the numpy port. Numpy defines a metaclass of dtype class, with its own C struct, the gist is:

NPY_NO_EXPORT PyTypeObject PyArrayDTypeMeta_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "numpy._DTypeMeta",
    .tp_basicsize = sizeof(PyArray_DTypeMeta),
    // ...
}

typedef struct {
    PyHeapTypeObject super;
    // Numpy specific data:
    PyArray_Descr *singleton;
    int type_num;
    // ...
} PyArray_DTypeMeta;

NPY_NO_EXPORT PyArray_DTypeMeta PyArrayDescr_Type = {
    {{
        /* NULL represents `type`, this is set to DTypeMeta at import time */
        PyVarObject_HEAD_INIT(NULL, 0)
        .tp_name = "numpy.dtype",
        .tp_basicsize = sizeof(PyArray_Descr),
        // ...
    },},
    // values for the numpy specific fields:
    .type_num = -1,
    .singleton = NULL,
    // ...
};

// ... in module init:
Py_SET_TYPE(&PyArrayDescr_Type, &PyArrayDTypeMeta_Type);
if (PyType_Ready(&PyArrayDescr_Type) < 0) {
    goto err;
}

In order to support this, HPyType_FromSpec should take metaclass as an additional parameter. There is even a TODO for this in HPy. The HPy side of things seems to be clear.

However, the issue is that PyType_FromSpecWithBases does not support metaclasses (https://bugs.python.org/issue15870). I think that we will have to copy the logic of PyType_FromSpecWithBases from CPython and delegate back to CPython only at the point where the original code calls PyType_Ready.

The problematic bit is that PyType_FromSpecWithBases calls PyType_GenericAlloc(&PyType_Type, nmembers), it should call tp_alloc of the metaclass as suggested in https://bugs.python.org/issue15870.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions