Skip to content

PyObject.ToString(IFormatProvider) is a bit generous with exceptions #2033

@rmadsen-ks

Description

@rmadsen-ks

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions