aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Python/pystate.c
diff options
context:
space:
mode:
authorEric Snow <ericsnowcurrently@gmail.com>2025-04-28 12:46:22 -0600
committerGitHub <noreply@github.com>2025-04-28 12:46:22 -0600
commitfe462f5a9122e1c2641b5369cbb88c4a5e822816 (patch)
tree2ab97dcc3c793827bc1e620fa8d65d07a3df837a /Python/pystate.c
parentc17238251fdf72861dfadcd581c77332b639bcb0 (diff)
downloadcpython-fe462f5a9122e1c2641b5369cbb88c4a5e822816.tar.gz
cpython-fe462f5a9122e1c2641b5369cbb88c4a5e822816.zip
gh-132775: Drop PyUnstable_InterpreterState_GetMainModule() (gh-132978)
We replace it with _Py_GetMainModule(), and add _Py_CheckMainModule(), but both in the internal-only C-API. We also add _PyImport_GetModulesRef(), which is the equivalent of _PyImport_GetModules(), but which increfs before the lock is released. This is used by a later change related to pickle and handling __main__.
Diffstat (limited to 'Python/pystate.c')
-rw-r--r--Python/pystate.c38
1 files changed, 32 insertions, 6 deletions
diff --git a/Python/pystate.c b/Python/pystate.c
index aba558279a6..ec19e3ae6a4 100644
--- a/Python/pystate.c
+++ b/Python/pystate.c
@@ -1210,14 +1210,40 @@ _PyInterpreterState_SetWhence(PyInterpreterState *interp, long whence)
PyObject *
-PyUnstable_InterpreterState_GetMainModule(PyInterpreterState *interp)
+_Py_GetMainModule(PyThreadState *tstate)
{
- PyObject *modules = _PyImport_GetModules(interp);
- if (modules == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
- return NULL;
+ // We return None to indicate "not found" or "bogus".
+ PyObject *modules = _PyImport_GetModulesRef(tstate->interp);
+ if (modules == Py_None) {
+ return modules;
+ }
+ PyObject *module = NULL;
+ (void)PyMapping_GetOptionalItem(modules, &_Py_ID(__main__), &module);
+ Py_DECREF(modules);
+ if (module == NULL && !PyErr_Occurred()) {
+ Py_RETURN_NONE;
}
- return PyMapping_GetItemString(modules, "__main__");
+ return module;
+}
+
+int
+_Py_CheckMainModule(PyObject *module)
+{
+ if (module == NULL || module == Py_None) {
+ if (!PyErr_Occurred()) {
+ (void)_PyErr_SetModuleNotFoundError(&_Py_ID(__main__));
+ }
+ return -1;
+ }
+ if (!Py_IS_TYPE(module, &PyModule_Type)) {
+ /* The __main__ module has been tampered with. */
+ PyObject *msg = PyUnicode_FromString("invalid __main__ module");
+ if (msg != NULL) {
+ (void)PyErr_SetImportError(msg, &_Py_ID(__main__), NULL);
+ }
+ return -1;
+ }
+ return 0;
}