【问题标题】:IronPython Override Builtin MethodIronPython 覆盖内置方法
【发布时间】:2015-08-09 16:34:10
【问题描述】:

我正在尝试覆盖 IronPython 提供的默认 __import__ 方法来处理数据库导入。我已经完成了这里提供的示例:https://stackoverflow.com/a/4127766/862319

到目前为止一切正常,但在 CLR 类型中存在与命名空间解析相关的小问题。我可以使用语法import ClrAssembly.Type 导入,但语法from ClrAssembly import Type 不起作用。这是一个小小的不便,但我想解决它。我怀疑 IronPython 中的 __import__ 方法有两个方法签名:

但是,上面的 SO 链接导致仅应用了一个带有 5 个参数签名的方法。这是设置后的 __import__ 变量:

我将如何构建一个自定义的 IronPython.Runtime.Types.BuiltinFunction,它映射到 2 个方法签名(DoDatabaseImport 的 5 个参数和 2 个参数版本)并将其分配回 __import__ 变量?

【问题讨论】:

    标签: c# ironpython


    【解决方案1】:

    希望这个答案对正在研究这个老问题的人有所帮助。

    查看 IronPython 2.7.7 的源代码,特别是来自的 builtin.cs 文件 https://github.com/IronLanguages/main/blob/3d9c336e1b6f0a86914a89ece171a22f48b0cc6e/Languages/IronPython/IronPython/Modules/Builtin.cs

    可以看到,2参数函数调用5参数重载时使用默认值。

    public static object __import__(CodeContext/*!*/ context, string name) {
        return __import__(context, name, null, null, null, -1);
    }
    

    为了复制这一点,我使用了具有类似默认值的委托。

    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);
    }
    

    覆盖内置导入函数如下所示

    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));
    }
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题。我的解决方案是搜索所有 clr 类型并将它们存储在 HashSet 中。如果 IronPython 尝试从 clr 导入一些东西,我会使用我自己的规则集并从 IronPython 调用内置导入器。这在一段时间内运行良好。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多