Debian Codegraph @

mypyc/lib-rt/module_shim.tmpl

raw
1 #include <Python.h>
2
3 PyMODINIT_FUNC
4 PyInit_{modname}(void)
5 {{
6 PyObject *tmp;
7 // Use ImportModuleLevel with a non-empty fromlist so Python returns the
8 // leaf submodule via sys.modules lookup, avoiding the top-down getattr
9 // walk done by PyImport_ImportModule. That walk fails when the shim runs
10 // during a parent package's __init__.py, because the parent's submodule
11 // attribute isn't set until after __init__ returns.
12 static PyObject *fromlist = NULL;
13 if (!fromlist) {{
14 fromlist = Py_BuildValue("(s)", "*");
15 if (!fromlist) return NULL;
16 }}
17 tmp = PyImport_ImportModuleLevel("{libname}", NULL, NULL, fromlist, 0);
18 if (!tmp) return NULL;
19 // Populate cross-group export tables lazily, just before we instantiate
20 // the per-module real init. Deferring this out of the shared lib's own
21 // PyInit keeps separate-mode compiled modules from recursively triggering
22 // sibling-package __init__.py mid-bootstrap.
23 // PyObject_GetOptionalAttrString would be cleaner, but it's 3.13+ and the
24 // shim deliberately #includes only <Python.h>, so we can't pull in the
25 // pythoncapi_compat.h shim from lib-rt here. AttributeError + PyErr_Clear
26 // is the portable form.
27 PyObject *deps_capsule = PyObject_GetAttrString(tmp, "ensure_deps");
28 if (deps_capsule != NULL) {{
29 int (*deps_func)(void) = (int (*)(void))PyCapsule_GetPointer(
30 deps_capsule, "{libname}.ensure_deps");
31 Py_DECREF(deps_capsule);
32 if (deps_func == NULL) {{
33 Py_DECREF(tmp);
34 return NULL;
35 }}
36 if (deps_func() < 0) {{
37 Py_DECREF(tmp);
38 return NULL;
39 }}
40 }} else {{
41 PyErr_Clear();
42 }}
43 PyObject *capsule = PyObject_GetAttrString(tmp, "init_{full_modname}");
44 Py_DECREF(tmp);
45 if (capsule == NULL) return NULL;
46 void *init_func = PyCapsule_GetPointer(capsule, "{libname}.init_{full_modname}");
47 Py_DECREF(capsule);
48 if (!init_func) {{
49 return NULL;
50 }}
51 return ((PyObject *(*)(void))init_func)();
52 }}
53
54 // distutils sometimes spuriously tells cl to export CPyInit___init__,
55 // so provide that so it chills out
56 PyMODINIT_FUNC PyInit___init__(void) {{ return PyInit_{modname}(); }}