Add compatiblity mode

This commit is contained in:
Dino Viehland 2025-09-22 06:43:55 -07:00
parent de281fd894
commit 41ab092407
8 changed files with 53 additions and 7 deletions

View file

@ -3862,6 +3862,7 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
PyObject *final_mod = NULL;
PyObject *mod = NULL;
PyObject *package = NULL;
PyObject *lazy_modules = NULL;
PyInterpreterState *interp = tstate->interp;
int has_from;
@ -3870,6 +3871,11 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
goto error;
}
if (globals != NULL &&
PyMapping_GetOptionalItem(globals, &_Py_ID(__lazy_modules__), &lazy_modules) < 0) {
goto error;
}
/* The below code is importlib.__import__() & _gcd_import(), ported to C
for added performance. */
@ -3888,6 +3894,24 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
goto error;
}
if (lazy_modules != NULL) {
// Check and see if the module is opting in w/o syntax for backwards compatibility
// with older Python versions.
int contains = PySequence_Contains(lazy_modules, name);
if (contains < 0) {
goto error;
} else if (contains == 1) {
_PyInterpreterFrame *frame = _PyEval_GetFrame();
if (frame == NULL) {
PyErr_SetString(PyExc_RuntimeError, "no current frame");
goto error;
}
final_mod = _PyImport_LazyImportModuleLevelObject(tstate, name, frame->f_builtins, globals,
locals, fromlist, level);
goto error;
}
}
mod = import_get_module(tstate, abs_name);
if (mod == NULL && _PyErr_Occurred(tstate)) {
goto error;
@ -3980,6 +4004,7 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
}
error:
Py_XDECREF(lazy_modules);
Py_XDECREF(abs_name);
Py_XDECREF(mod);
Py_XDECREF(package);