File tree Expand file tree Collapse file tree 1 file changed +17
-7
lines changed
Expand file tree Collapse file tree 1 file changed +17
-7
lines changed Original file line number Diff line number Diff 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 ;
You can’t perform that action at this time.
0 commit comments