IronPython built-in method
I am trying to override the default __import__ method provided by IronPython to handle database imports. I've already gone through the example given here: qaru.site/questions/746747 / ...
Everything works so far, but there is a small problem with namespace resolution in CLR types. I can import using syntax import ClrAssembly.Type
but the syntax from ClrAssembly import Type
doesn't work. This is a slight inconvenience, but I would like it to be resolved. My suspicion is that IronPython has two method signatures bound to __import__method:
But the SO link above shows only one method applied with 5 parameter signature. Below is the __import__ variable:
How do I go about creating a custom IronPython.Runtime.Types.BuiltinFunction
one that maps to 2 method signatures (5 param and 2 param versions of DoDatabaseImport) and assign it back to the __import__ variable?
source to share
Hope this answer helps someone looking at this old question.
Looking at the source for IronPython 2.7.7, specifically the builtin.cs file from https://github.com/IronLanguages/main/blob/3d9c336e1b6f0a86914a89ece171a22f48b0cc6e/Languages/IronPython/IronPython/Modules/Built
you can see that the parameter 2 function causes an overload of parameter 5 with default values.
public static object __import__(CodeContext/*!*/ context, string name) {
return __import__(context, name, null, null, null, -1);
}
To reproduce this, I used a delegate with similar defaults.
delegate object ImportDelegate(CodeContext context, string moduleName, object globals = null, object locals = null, object fromlist = null, int level = -1);
protected object ImportOverride(CodeContext context, string moduleName, object globals = null, object locals = null, object fromlist = null, int level = -1)
{
// do custom import logic here
return IronPython.Modules.Builtin.__import__(context, moduleName, globals, locals, fromlist, level);
}
Override built-in import function is shown below
private ScriptEngine pyengine;
private ScriptingEngine()
{
Dictionary<string, object> options = new Dictionary<string, object>();
options["Debug"] = true;
pyengine = Python.CreateEngine(options);
var builtinscope = Python.GetBuiltinModule(pyengine);
builtinscope.SetVariable("__import__", new ImportDelegate(ImportOverride));
}
source to share