I'm using Python.NET to load a C# Assembly to call C# code from Python. This works pretty cleanly, however I am having an issue calling a method that looks like this:
A method within Our.Namespace.Proj.MyRepo:
OutputObject GetData(string user, int anID, int? anOptionalID= null)
I can call the method for the case where the optional third argument is present but can't figure out what to pass for the third argument to match the null case.
import clr
clr.AddReference("Our.Namespace.Proj")
import System
from Our.Namespace.Proj import MyRepo
_repo = MyRepo()
_repo.GetData('me', System.Int32(1), System.Int32(2)) # works!
_repo.GetData('me', System.Int32(1)) # fails! TypeError: No method matches given arguments
_repo.GetData('me', System.Int32(1), None) # fails! TypeError: No method matches given arguments
The iPython Notebook indicates that the last argument should be of type:
System.Nullable`1[System.Int32]
Just not sure how to create an object that will match the Null case.
Any suggestions on how to create a C# recognized Null object? I assumed passing the native Python None would work, but it does not.
I have no way to test this, but try
Since you're saying that the optional parameter is
Nullable
, you need to create a newNullable
object of typeInt32
, ornew System.Nullable<int>()
in C# code.I would have assumed that the first failing example would work, given that this is how optional parameters work in C#; calling the function without specifying the parameter at all.
[EDIT]
This has been merged to pythonnet:
https://github.com/pythonnet/pythonnet/pull/460
I ran into the same issue with nullable primitives -- it seems to me that Python.NET doesn't support these types. I got around the problem by adding the following code in Python.Runtime.Converter.ToManagedValue() (\src\runtime\converter.cs)
I placed this code right underneath
https://github.com/pythonnet/pythonnet/blob/4df6105b98b302029e524c7ce36f7b3cb18f7040/src/runtime/converter.cs#L320
You have to pass argument to generic function
System.Nullable[System.Int32](0)