Environment
- Pythonnet version 3.0.1:
- Python version --:
- Operating System --:
- .NET Runtime: --
Details
PyObject implements IConvertible and therefore ToString(IFormatProvider).
For many types of objects PyObject.ToString(IFormatProvider) throws an InvalidCastException, and I'd argue that this is a problem.
According to the MSDN doc of the IConvertible interface, it should only throw an exception if there is no meaningful conversion. I'd argue that most python objects can be converted to a string, just like is done with the regular PyObject.ToString() implementation. So maybe PyObject, should not throw whenever the object isn't a string as it does currently:
string managedString = Python.Runtime.Runtime.GetManagedString(in value);
if (managedString != null)
{
result = (object) managedString;
return true;
}
// else return false / error.
From MSDN:
If there is no meaningful conversion to a common language runtime type, then a particular interface method implementation throws [InvalidCastException](https://learn.microsoft.com/en-us/dotnet/api/system.invalidcastexception?view=net-7.0). For example, if this interface is implemented on a Boolean type, the implementation of the [ToDateTime](https://learn.microsoft.com/en-us/dotnet/api/system.iconvertible.todatetime?view=net-7.0) method throws an exception because there is no meaningful [DateTime](https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=net-7.0) equivalent to a Boolean type.
Environment
Details
PyObject implements IConvertible and therefore ToString(IFormatProvider).
For many types of objects PyObject.ToString(IFormatProvider) throws an InvalidCastException, and I'd argue that this is a problem.
According to the MSDN doc of the IConvertible interface, it should only throw an exception if there is no meaningful conversion. I'd argue that most python objects can be converted to a string, just like is done with the regular PyObject.ToString() implementation. So maybe PyObject, should not throw whenever the object isn't a string as it does currently:
From MSDN:
If there is no meaningful conversion to a common language runtime type, then a particular interface method implementation throws [InvalidCastException](https://learn.microsoft.com/en-us/dotnet/api/system.invalidcastexception?view=net-7.0). For example, if this interface is implemented on a Boolean type, the implementation of the [ToDateTime](https://learn.microsoft.com/en-us/dotnet/api/system.iconvertible.todatetime?view=net-7.0) method throws an exception because there is no meaningful [DateTime](https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=net-7.0) equivalent to a Boolean type.