Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f0d0aeb

Browse files
committed
set __file__, __doc__ and __class__ on ModuleObject to make the managed
modules behave better in ipython (%autoreload expects __file__ to be set and the ipython help ? expects __class__ to be set).
1 parent afce8dc commit f0d0aeb

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

pythonnet/src/runtime/assemblymanager.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,16 @@ public static bool IsValidNamespace(string name) {
314314
return namespaces.ContainsKey(name);
315315
}
316316

317+
//===================================================================
318+
// Returns list of assemblies that declare types in a given namespace
319+
//===================================================================
320+
321+
public static IEnumerable<Assembly> GetAssemblies(string nsname) {
322+
if (!namespaces.ContainsKey(nsname))
323+
return new List<Assembly>();
324+
325+
return namespaces[nsname].Keys;
326+
}
317327

318328
//===================================================================
319329
// Returns the current list of valid names for the input namespace.

pythonnet/src/runtime/moduleobject.cs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,27 @@ public ModuleObject(string name) : base() {
3737
cache = new Dictionary<string, ManagedType>();
3838
_namespace = name;
3939

40+
// Use the filename from any of the assemblies just so there's something for
41+
// anything that expects __file__ to be set.
42+
string filename = "unknown";
43+
string docstring = "Namespace containing types from the following assemblies:\n\n";
44+
foreach (Assembly a in AssemblyManager.GetAssemblies(name)) {
45+
filename = a.Location;
46+
docstring += "- " + a.FullName + "\n";
47+
}
48+
4049
dict = Runtime.PyDict_New();
4150
IntPtr pyname = Runtime.PyString_FromString(moduleName);
51+
IntPtr pyfilename = Runtime.PyString_FromString(filename);
52+
IntPtr pydocstring = Runtime.PyString_FromString(docstring);
53+
IntPtr pycls = TypeManager.GetTypeHandle(this.GetType());
4254
Runtime.PyDict_SetItemString(dict, "__name__", pyname);
43-
Runtime.PyDict_SetItemString(dict, "__file__", Runtime.PyNone);
44-
Runtime.PyDict_SetItemString(dict, "__doc__", Runtime.PyNone);
55+
Runtime.PyDict_SetItemString(dict, "__file__", pyfilename);
56+
Runtime.PyDict_SetItemString(dict, "__doc__", pydocstring);
57+
Runtime.PyDict_SetItemString(dict, "__class__", pycls);
4558
Runtime.Decref(pyname);
59+
Runtime.Decref(pyfilename);
60+
Runtime.Decref(pydocstring);
4661

4762
Marshal.WriteIntPtr(this.pyHandle, ObjectOffset.DictOffset(this.pyHandle), dict);
4863

0 commit comments

Comments
 (0)