Skip to content

Commit cbc4d3f

Browse files
Set __globals__ to __main__.__dict__ for stateless funcs.
1 parent 44a39a5 commit cbc4d3f

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

Python/crossinterp_data_lookup.h

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -695,16 +695,26 @@ _PyFunction_FromXIData(_PyXIData_t *xidata)
695695
return NULL;
696696
}
697697
// Create a new function.
698+
// For stateless functions (no globals) we use __main__ as __globals__,
699+
// just like we do for builtins like exec().
698700
assert(PyCode_Check(code));
699-
PyObject *globals = PyDict_New();
701+
PyThreadState *tstate = _PyThreadState_GET();
702+
PyObject *globals = _PyEval_GetGlobalsFromRunningMain(tstate); // borrowed
700703
if (globals == NULL) {
701-
Py_DECREF(code);
702-
return NULL;
704+
if (_PyErr_Occurred(tstate)) {
705+
Py_DECREF(code);
706+
return NULL;
707+
}
708+
globals = PyDict_New();
709+
if (globals == NULL) {
710+
Py_DECREF(code);
711+
return NULL;
712+
}
703713
}
704-
PyThreadState *tstate = _PyThreadState_GET();
705-
if (PyDict_SetItem(globals, &_Py_ID(__builtins__),
706-
tstate->interp->builtins) < 0)
707-
{
714+
else {
715+
Py_INCREF(globals);
716+
}
717+
if (_PyEval_EnsureBuiltins(tstate, globals, NULL) < 0) {
708718
Py_DECREF(code);
709719
Py_DECREF(globals);
710720
return NULL;

0 commit comments

Comments
 (0)