Skip to content

Implement IConvertible on PyObject #1762

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/runtime/Converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ internal static int ToInt32(BorrowedReference value)
/// <summary>
/// Convert a Python value to an instance of a primitive managed type.
/// </summary>
private static bool ToPrimitive(BorrowedReference value, Type obType, out object? result, bool setError)
internal static bool ToPrimitive(BorrowedReference value, Type obType, out object? result, bool setError)
{
result = null;
if (obType.IsEnum)
Expand Down
2 changes: 2 additions & 0 deletions src/runtime/PythonTypes/PyFloat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,5 +101,7 @@ public static PyFloat AsFloat(PyObject value)
PythonException.ThrowIfIsNull(op);
return new PyFloat(op.Steal());
}

public override TypeCode GetTypeCode() => TypeCode.Double;
}
}
2 changes: 2 additions & 0 deletions src/runtime/PythonTypes/PyInt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -230,5 +230,7 @@ public string ToString(string format, IFormatProvider formatProvider)
using var _ = Py.GIL();
return ToBigInteger().ToString(format, formatProvider);
}

public override TypeCode GetTypeCode() => TypeCode.Int64;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally, this is wrong.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docs are a bit unclear on this function. I used this as an "should almost always work" value, the InvalidCastException might still be thrown if the conversion fails. We could drop the GetTypeCode overrides entirely and just return TypeCode.Object if you'd prefer that.

Copy link
Member

@lostmsu lostmsu Apr 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't say for others, just for this one. Honestly, not sure if anyone ever uses this. Our own code assumes TypeCode.Int64 refers to System.Int64, so removing might be a good idea.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I follow. GetTypeCode is supposed to be a hint that allows you to write a switch like

switch (convertible.GetTypeCode()) {
    case TypeCode.Int64:
        return Convert.ToInt64(convertible);
}

It doesn't mean that the object is a System.Int64 already.

Copy link
Member

@lostmsu lostmsu Apr 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You seem to be correct on that. Still not sure Int64 is valid for this specific case, but float and string probably are. I am fine either way though. I don't think we will get people complaining about this returning Int64 any time soon.

}
}
53 changes: 53 additions & 0 deletions src/runtime/PythonTypes/PyObject.IConvertible.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System;

namespace Python.Runtime;

public partial class PyObject : IConvertible
{
public virtual TypeCode GetTypeCode() => TypeCode.Object;

private T DoConvert<T>()
{
using var _ = Py.GIL();
if (Converter.ToPrimitive(Reference, typeof(T), out object? result, setError: false))
{
return (T)result!;
}
else
{
throw new InvalidCastException();
}
}

public bool ToBoolean(IFormatProvider provider) => DoConvert<bool>();
public byte ToByte(IFormatProvider provider) => DoConvert<byte>();
public char ToChar(IFormatProvider provider) => DoConvert<char>();
public short ToInt16(IFormatProvider provider) => DoConvert<short>();
public int ToInt32(IFormatProvider provider) => DoConvert<int>();
public long ToInt64(IFormatProvider provider) => DoConvert<long>();
public sbyte ToSByte(IFormatProvider provider) => DoConvert<sbyte>();
public ushort ToUInt16(IFormatProvider provider) => DoConvert<ushort>();
public uint ToUInt32(IFormatProvider provider) => DoConvert<uint>();
public ulong ToUInt64(IFormatProvider provider) => DoConvert<ulong>();

public float ToSingle(IFormatProvider provider) => DoConvert<float>();
public double ToDouble(IFormatProvider provider) => DoConvert<double>();

public string ToString(IFormatProvider provider) => DoConvert<string>();

public DateTime ToDateTime(IFormatProvider provider) => throw new InvalidCastException();
public decimal ToDecimal(IFormatProvider provider) => throw new InvalidCastException();

public object ToType(Type conversionType, IFormatProvider provider)
{
if (Converter.ToManaged(Reference, conversionType, out object? result, setError: false))
{
return result!;
}
else
{
throw new InvalidCastException();
}
}

}
2 changes: 2 additions & 0 deletions src/runtime/PythonTypes/PyString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,7 @@ public static bool IsStringType(PyObject value)
{
return Runtime.PyString_Check(value.obj);
}

public override TypeCode GetTypeCode() => TypeCode.String;
}
}
7 changes: 7 additions & 0 deletions tests/test_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,3 +670,10 @@ def test_int_param_resolution_required():
data = list(mri.MethodA(0x100000000, 10))
assert len(data) == 10
assert data[0] == 0

def test_iconvertible_conversion():
change_type = System.Convert.ChangeType

assert 1024 == change_type(1024, System.Int32)
assert 1024 == change_type(1024, System.Int64)
assert 1024 == change_type(1024, System.Int16)