[3.14] gh-135443: Sometimes Fall Back to __main__.__dict__ For Globals (gh-135593)

For several builtin functions, we now fall back to __main__.__dict__ for the globals
when there is no current frame and _PyInterpreterState_IsRunningMain() returns
true.  This allows those functions to be run with Interpreter.call().

The affected builtins:

* exec()
* eval()
* globals()
* locals()
* vars()
* dir()

We take a similar approach with "stateless" functions, which don't use any
global variables.

(cherry picked from commit a450a0ddec, AKA gh-135491)

Co-authored-by: Eric Snow <ericsnowcurrently@gmail.com>
This commit is contained in:
Miss Islington (bot) 2025-06-17 01:59:30 +02:00 committed by GitHub
parent 7aeddeaf93
commit 2b1c0a76dc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 394 additions and 68 deletions

View file

@ -1973,9 +1973,25 @@ _dir_locals(void)
PyObject *names;
PyObject *locals;
locals = _PyEval_GetFrameLocals();
if (locals == NULL)
if (_PyEval_GetFrame() != NULL) {
locals = _PyEval_GetFrameLocals();
}
else {
PyThreadState *tstate = _PyThreadState_GET();
locals = _PyEval_GetGlobalsFromRunningMain(tstate);
if (locals == NULL) {
if (!_PyErr_Occurred(tstate)) {
locals = _PyEval_GetFrameLocals();
assert(_PyErr_Occurred(tstate));
}
}
else {
Py_INCREF(locals);
}
}
if (locals == NULL) {
return NULL;
}
names = PyMapping_Keys(locals);
Py_DECREF(locals);