Skip to content

It is awkward to check whether an obj is of a particular heap type (defined in an extension module) #133161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
iritkatriel opened this issue Apr 29, 2025 · 3 comments
Labels
topic-C-API type-feature A feature request or enhancement

Comments

@iritkatriel
Copy link
Member

I wanted to check whether an object is of type array and ended up doing this:

    PyObject *exc = PyErr_GetRaisedException();
    PyObject *module = PyType_GetModuleByDef(Py_TYPE(lhs), &arraymodule);
    if (module == NULL) {
        if (!PyErr_Occurred() || PyErr_ExceptionMatches(PyExc_TypeError)) {
            /* lhs is not an array instance - ignore the TypeError (if any) */
            PyErr_SetRaisedException(exc);
            return 0;
        }
        else {
            _PyErr_ChainExceptions1(exc);
            return -1;
        } 
    }   
    PyErr_SetRaisedException(exc);
    return array_Check(lhs, get_array_state(module));

CC @ericsnowcurrently @encukou

@encukou
Copy link
Member

encukou commented Apr 29, 2025

In 3.14, add {Py_tp_token, Py_TP_USE_SPEC} to array_slots, then use PyType_GetBaseByToken(lhs, &array_spec, NULL)

@mdboom
Copy link
Contributor

mdboom commented Apr 30, 2025

Is this something that should be documented in the "isolating extension modules" migration guide? Seems like it would be easy for extension authors to miss.

@iritkatriel
Copy link
Member Author

In 3.14, add {Py_tp_token, Py_TP_USE_SPEC} to array_slots, then use PyType_GetBaseByToken(lhs, &array_spec, NULL)

This is better. Would be nicer if it just returned a Boolean so I won't need to deal with exception state.

@picnixz picnixz added the type-feature A feature request or enhancement label May 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic-C-API type-feature A feature request or enhancement
Projects
None yet
Development

No branches or pull requests

4 participants