Skip to content

Commit 5354bc9

Browse files
committed
Create a new module for importing the embedded clr.py file into as the
globals dictionary doesn't exist when not being run inside a python process (i.e. when embedded).
1 parent 263e249 commit 5354bc9

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/runtime/pythonengine.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -150,25 +150,29 @@ public static void Initialize() {
150150
IntPtr clr = Python.Runtime.ImportHook.GetCLRModule();
151151
IntPtr clr_dict = Runtime.PyModule_GetDict(clr);
152152

153-
IntPtr globals = Runtime.PyEval_GetGlobals();
154153
PyDict locals = new PyDict();
155154
try
156155
{
156+
IntPtr module = Runtime.PyImport_AddModule("clr._extras");
157+
IntPtr module_globals = Runtime.PyModule_GetDict(module);
157158
IntPtr builtins = Runtime.PyEval_GetBuiltins();
158-
Runtime.PyDict_SetItemString(locals.Handle, "__builtins__", builtins);
159+
Runtime.PyDict_SetItemString(module_globals, "__builtins__", builtins);
159160

160161
var assembly = Assembly.GetExecutingAssembly();
161162
using (Stream stream = assembly.GetManifestResourceStream("Python.Runtime.resources.clr.py"))
162163
using (StreamReader reader = new StreamReader(stream))
163164
{
164165
// add the contents of clr.py to the module
165166
string clr_py = reader.ReadToEnd();
166-
PyObject result = RunString(clr_py, globals, locals.Handle);
167+
PyObject result = RunString(clr_py, module_globals, locals.Handle);
167168
if (null == result)
168169
throw new PythonException();
169170
result.Dispose();
170171
}
171172

173+
// add the imported module to the clr module, and copy the API functions
174+
// and decorators into the main clr module.
175+
Runtime.PyDict_SetItemString(clr_dict, "_extras", module);
172176
foreach (PyObject key in locals.Keys())
173177
{
174178
if (!key.ToString().StartsWith("_")){

0 commit comments

Comments
 (0)