4

I would like to use IronPython to override a method from a dll, so that all future calls to that method go to the python implementation instead. I was hoping to base it on the technique from the accepted answer here.

So I tried making a dll with just the following class:

namespace ClassLibrary1
{
    public class Class1
    {
        public static string test()
        {
            return "test";
        }
    }
}

Then I did the following in IronPython:

import clr
clr.AddReference("ClassLibrary1")

import ClassLibrary1

def _override():
    return "george"

ClassLibrary1.Class1.test = _override;

print ClassLibrary1.Class1.test();

However, when running the python code, I get the following exception:

An exception of type 'System.MissingMemberException' occurred in Snippets.debug.scripting but was not handled in user code

Additional information: attribute 'test' of 'Class1' object is read-only

Is there any way to accomplish what I am looking for?

Community
  • 1
  • 1
Daniel Centore
  • 3,220
  • 1
  • 18
  • 39

2 Answers2

1

Just to extend Roland's answer, consider writing a wrapping python module. I have never worked with IronPython, but I believe you can fix the solution if an issue appears.

# class_library_1_wrapper.py
import clr
clr.AddReference("ClassLibrary1")
import ClassLibrary1 


class Class1:
    def __init__(self):
        self._clr_object = ClassLibrary1.Class1()

    def some_method():
        return self._clr_object.SomeMethod()

    @staticmethod
    def test():
        return "george"

This approach is suggested by Cython developers when importing C++ classes. The other benefit is you weaken your dependency on "ClassLibrary1" and can fallback to pure IronPython implementation of Class1 without letting other modules know:

# class_library_1_wrapper.py
import clr
clr.AddReference("ClassLibrary1")

try:
    import ClassLibrary1
except ImportError:
    print 'sorry, no speed-ups'
    # Class1 IronPython implementation here
else:
    # Implement Class1 as described in the first snippet.

This approach can be found in Werkzeug Python library.

u354356007
  • 3,205
  • 15
  • 25
0

What you are attempting is called a monkey patch. It is not actually an override, but a dynamic replacement of an attribute at runtime.

Monkey patching is specific to python, so it isn't guaranteed for non-python classes.

Instead, look into deriving a new python class from your C# class, and override the method there.

Community
  • 1
  • 1
rask004
  • 552
  • 5
  • 15