gh-135443: Sometimes Fall Back to __main__.__dict__ For Globals (gh-135491)

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.
This commit is contained in:
Eric Snow 2025-06-16 17:34:19 -06:00 committed by GitHub
parent 68b7e1a667
commit a450a0ddec
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 394 additions and 68 deletions

View file

@ -2084,9 +2084,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);