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

Skip to content

IronPython compatibility issue - explicit interface implementationΒ #22

@koubaa

Description

@koubaa

🐞 Description of the bug

Explicit interface implementation is a feature of C# that allows a class to implement an interface but hide the implementation of users of the class, unless they explictly cast to the interface.

πŸ“ Steps to reproduce

The following code leads to the exception AttributeError: 'NamedObject' object has no attribute 'Id'

namespace TestInheritance {
    public interface IObject {
        int Id { get; }
    }

    public class NamedObject : IObject {
        private int _objectId;
        private string _name;

        public NamedObject(string name, int objectId) {
            _objectId = objectId;
            _name = name;
        }

        public string Name => _name;
#if PUBLIC_INHERITANCE
        public int Id => _objectId;
#else
        int IObject.Id => _objectId;
#endif
    }

  class Program {
    static void Main(string[] args) {
      var pyCode = @"
import TestInheritance
o = TestInheritance.NamedObject("hello", 1)
print(o.Id)";

      Runtime.PythonDLL = "libpython3.9.dylib";
      PythonEngine.Initialize();

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

      PythonEngine.Shutdown();
    }
  }
}

If the define #PUBLIC_INHERITANCE is set, the exception goes away. The current behavior is correct, according to how explicit interface implementation is meant to work in C#. However, IronPython allows python to call explicit interfaces without casting. This means that python scripts written for IronPython will not work for CPython. ansys-pythonnet should have an opt-in to support such calls without making it the default.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions