0

I am writing a Python 3 C extension where I want to use a MappingProxyType (from types import MappingProxyType). From what I saw in the Cpython source code, MappingProxyType is written in Python and not in C.

How can I use this type from C? I imagine there must be something like an C-level "import" and then I could find the PyObject (or rather, PyTypeObject) from the name as a C string.

jleeothon
  • 2,907
  • 4
  • 19
  • 35

1 Answers1

1

There's a C API for for importing modules. Then you just need to get the MappingProxyType type attribute from the module:

static PyTypeObject *import_MappingProxyType(void) {
    PyObject *m = PyImport_ImportModule("types");
    if (!m) return NULL;
    PyObject *t = PyObject_GetAttrString(m, "MappingProxyType");
    Py_DECREF(m);
    if (!t) return NULL;
    if (PyType_Check(t))
        return (PyTypeObject *) t;
    Py_DECREF(t);
    PyErr_SetString(PyExc_TypeError, "not the MappingProxyType type");
    return NULL;
}
tynn
  • 38,113
  • 8
  • 108
  • 143
  • You forgot to check for errors on the getattr. In practice it is unlikely to fail, but somebody could have monkey-patched out the module. – Kevin Feb 14 '16 at 23:10
  • @Kevin it's not necessary. If `t` is `NULL`, the function just returns `NULL`. `t` never gets used, so it's safe. – tynn Feb 14 '16 at 23:18
  • And what if `t` is `None` or something that isn't a `PyTypeObject`? – Kevin Feb 15 '16 at 00:45