Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a C# Nullable Int32 within Python (using Python.NET) to call a C# method with an optional int argument

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.

like image 577
skulz00 Avatar asked Nov 04 '14 18:11

skulz00


1 Answers

[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)

if( obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>) )
{
    if( value == Runtime.PyNone )
    {
        result = null;
        return true;
    }
    // Set type to underlying type
    obType = obType.GetGenericArguments()[0];
}

I placed this code right underneath

if (value == Runtime.PyNone && !obType.IsValueType) {
    result = null;
    return true;
}

https://github.com/pythonnet/pythonnet/blob/4df6105b98b302029e524c7ce36f7b3cb18f7040/src/runtime/converter.cs#L320

like image 70
antchi Avatar answered Sep 17 '22 19:09

antchi