Skip to content

Can not call inherited method on nested class, when another nested class inherits from it and defines an override. #1787

Open
@Algoryx-NilsHjelte

Description

@Algoryx-NilsHjelte

This is a very specific setup with classes and inheritance, but is exactly what happened to us and where pythonnet does not do the right thing.

It is closely related to #1420 but a slightly different configuration.

Here is code to reproduce the issue:

namespace pythonnet_testing {
  public class Creator {
    public static object CreateObject() =>
      new BaseClass.NestedClass();
  }

  public class BaseClass {


    public virtual string GetSignal() =>
      "hello";

    public class NestedClass : BaseClass {
      // NOTE: This is using the default `GetSignal` implementation
    }

    // NOTE: This class inherits from the nested class, and overrides the method in the base class
    // When this class is defined, we can no longer call `GetSignal` on instances of `NestedClass`
    // ==> `Unhandled exception. Python.Runtime.PythonException: 'NestedClass' object has no attribute 'GetSignal'`
    public class InheritFromNested : BaseClass.NestedClass {
      public override string GetSignal() =>
        "override";
    }
  }


  class Program {
    static void Main(string[] args) {
      var pyCode = @"
import pythonnet_testing
o = pythonnet_testing.Creator.CreateObject()
print(f'Method call: {o.GetSignal()}')
      ";
      Runtime.PythonDLL = "libpython3.9.dylib";
      PythonEngine.Initialize();

      using (Py.GIL()) {
        PythonEngine.Exec(pyCode);
      }

      PythonEngine.Shutdown();
    }
  }
}

NOTE: If I remove the InheritFromNested class, then the call to o.GetSignal will resolve the proper inherited virtual base method.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions