Skip to content

Commit

Permalink
Fix: allow calling C# class constructor with snake-cased arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
jhonabreul committed May 23, 2024
1 parent 8fb227a commit 8600d8d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/embed_tests/TestMethodBinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -898,6 +898,24 @@ def call_method(instance):
Assert.IsFalse(Exceptions.ErrorOccurred());
}

[Test]
public void BindsConstructorToSnakeCasedArgumentsVersion()
{
using var _ = Py.GIL();

var module = PyModule.FromString("CallsCorrectOverloadWithoutErrors", @"
from clr import AddReference
AddReference(""System"")
from Python.EmbeddingTest import *
def create_instance():
return TestMethodBinder.CSharpModel(some_argument=1, another_argument=""another argument value"")
");
var exception = Assert.Throws<ClrBubbledException>(() => module.GetAttr("create_instance").Invoke());
var sourceException = exception.InnerException;
Assert.IsInstanceOf<NotImplementedException>(sourceException);
Assert.AreEqual("Constructor with arguments", sourceException.Message);
}

// Used to test that we match this function with Py DateTime & Date Objects
public static int GetMonth(DateTime test)
Expand All @@ -918,6 +936,12 @@ public CSharpModel()
new TestImplicitConversion()
};
}

public CSharpModel(int someArgument, string anotherArgument = "another argument")
{
throw new NotImplementedException("Constructor with arguments");
}

public void TestList(List<TestImplicitConversion> conversions)
{
if (!conversions.Any())
Expand Down
5 changes: 5 additions & 0 deletions src/runtime/ClassManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,11 @@ void AddMember(string name, string snakeCasedName, bool isStaticReadonlyCallable
methodList = methods[name] = new ();
}
methodList.Add(ctor, true);
// Same constructor, but with snake-cased arguments
if (ctor.GetParameters().Any(pi => pi.Name.ToSnakeCase() != pi.Name))
{
methodList.Add(ctor, false);
}
continue;

case MemberTypes.Property:
Expand Down

0 comments on commit 8600d8d

Please sign in to comment.