Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Don't use repr in __str__. Clean up unneeded tests
  • Loading branch information
koubaa committed Oct 16, 2019
commit accc7978c657f0e524eb32f1d2a4cdc2a6e08db1
27 changes: 0 additions & 27 deletions src/runtime/classbase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,34 +233,7 @@ public static IntPtr tp_str(IntPtr ob)
}
try
{
//As per python doc:
//The return value must be a string object. If a class defines __repr__() but not __str__(),
//then __repr__() is also used when an “informal” string representation of instances of that
//class is required.
//In C#, everything provides ToString(), so the check here will be whether the type explicitly
//provides ToString() or if it is language provided (i.e. the fully qualified type name as a string)

//First check which type in the object hierarchy provides ToString()
//ToString has two "official" overloads so loop over GetMethods to get the one without parameters
var instType = co.inst.GetType();
var method = instType.GetMethod("ToString", new Type[]{});
if (method.DeclaringType != typeof(object))
{
//match! something other than object provides a parameter-less overload of ToString
return Runtime.PyString_FromString(co.inst.ToString());
}

//If the object defines __repr__, call it.
System.Reflection.MethodInfo reprMethodInfo = instType.GetMethod("__repr__");
if (reprMethodInfo != null && reprMethodInfo.IsPublic)
{
var reprString = (string)reprMethodInfo.Invoke(co.inst, null);
return Runtime.PyString_FromString(reprString);
}

//otherwise fallback to object's ToString() implementation
return Runtime.PyString_FromString(co.inst.ToString());

}
catch (Exception e)
{
Expand Down
6 changes: 0 additions & 6 deletions src/tests/test_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,6 @@ def test_system_string():
assert str(ob) == "hello"
assert "<System.String object at " in ob.__repr__()

def test_repr_only():
"""Test class implementing __repr__() but not ToString()"""
ob = ReprTest.Foo()
assert str(ob) == "I implement __repr__() but not ToString()!"
assert ob.__repr__() == "I implement __repr__() but not ToString()!"

def test_str_only():
"""Test class implementing ToString() but not __repr__()"""
ob = ReprTest.Bar()
Expand Down