PyImport_Import does not fall back to default builtins
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Bug report
Bug description:
When importing a module with PyImport_Import() inside an already running python which does have limited globals, the import fails due to missing __builtins__: https://github.com/python/cpython/blob/01ba7df49966eaf14f44962a77898840c70dda96/Python/import.c#L3914-L3921
It feels similar to this issue: https://github.com/python/cpython/pull/24564 but with a slightly different setup.
Originally reported for pyo3 here: https://github.com/PyO3/pyo3/issues/4913
Minimal reproducer below, fuller reproducer can be found here: https://gitlab.com/nertpinx/cpython_repr
#include <Python.h>
PyObject *
func(PyObject *self __attribute__((unused)),
PyObject *arg)
{
return PyImport_Import(arg);
}
static PyMethodDef method_def = {
.ml_name = "func",
.ml_meth = func,
.ml_flags = METH_NOARGS,
.ml_doc = "Reproducer function",
};
int
main(int argc __attribute__((unused)),
char **argv __attribute__((unused)))
{
Py_InitializeEx(0);
PyObject *program = NULL;
PyObject *globals = NULL;
PyObject *supermodule = NULL;
PyObject *py_func = NULL;
supermodule = PyUnicode_FromString("supermodule");
py_func = PyCFunction_NewEx(&method_def, NULL, supermodule);
globals = PyDict_New();
PyDict_SetItemString(globals, "func", py_func);
program = Py_CompileString("func()", "<string>", Py_file_input);
PyEval_EvalCode(program, globals, NULL);
if (PyErr_Occurred()) {
PyErr_Print();
return 1;
}
return 0;
}
CPython versions tested on:
3.13
Operating systems tested on:
Linux
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the referenced import.c lines around 3914-3921 and build the minimal C reproducer against CPython 3.13. Check how PyImport_Import handles globals without builtins, then add a regression test covering the limited-globals setup. Done means the import succeeds using default builtins rather than failing with missing builtins.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c, python
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100