Skip to content

Commit 657faff

Browse files
Match str() for enums and keep the default repr for plain structs
Enum.ToString() gives the .NET member name, while str() of an enum gives the Python-facing one (MONDAY), so repr() now uses the same name. ValueType.ToString() only returns the type name, so structs without their own ToString() keep the default object repr. Add a CHANGELOG entry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 50f9c47 commit 657faff

3 files changed

Lines changed: 21 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
1010
### Added
1111

1212
- Extension methods declared in non-framework assemblies are bound to the type they extend, so they can be called from the instance like in C# (e.g. `order_status.is_open()`). Those marked `[EditorBrowsable(EditorBrowsableState.Never)]`, or declared in a class marked so, keep their static form only
13+
- `repr()` of a .NET object whose type overrides `ToString()` returns that text (the Python-facing member name for enums), so containers of such objects print readably (e.g. `[SPY, AIG]`), unless the type declares a public `__repr__()`
1314
- Types with an implicit conversion to a numeric type support Python arithmetic, comparisons, `float()` and `int()` through that conversion, behaving like a Python `int` for integral conversions and a `float` otherwise, unless they declare or inherit the operator
1415
- Ability to instantiate new .NET arrays using `Array[T](dim1, dim2, ...)` syntax
1516
- Python operator method will call C# operator method for supported binary and unary operators ([#1324][p1324]).

‎src/runtime/Types/ClassBase.cs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -375,13 +375,16 @@ public static NewReference tp_repr(BorrowedReference ob)
375375
return reprString is null ? new NewReference(Runtime.PyNone) : Runtime.PyString_FromString(reprString);
376376
}
377377

378-
// show an overridden ToString() so containers of .NET objects print readably: [SPY, AIG]
379-
if (instType.GetMethod("ToString", Type.EmptyTypes)?.DeclaringType != typeof(object))
378+
// show an overridden ToString() so containers of .NET objects print readably: [SPY, AIG].
379+
// ValueType.ToString() only returns the type name, so structs without their own keep the default
380+
var toStringType = instType.GetMethod("ToString", Type.EmptyTypes)?.DeclaringType;
381+
if (toStringType != typeof(object) && toStringType != typeof(ValueType))
380382
{
381383
string? text = null;
382384
try
383385
{
384-
text = co.inst.ToString();
386+
// enums match their str(), the Python-facing member name
387+
text = co.inst is Enum enumValue ? EnumObject.ToPythonString(enumValue) : co.inst.ToString();
385388
}
386389
catch (Exception)
387390
{

‎tests/test_repr.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,20 @@ def test_str_only_nested_in_list():
3030
obs = [ReprTest.Bar(), ReprTest.Bar()]
3131
assert str(obs) == "[I implement ToString() but not __repr__()!, I implement ToString() but not __repr__()!]"
3232

33+
def test_enum():
34+
"""Test enums show the same Python-facing member name as str()"""
35+
from System import DayOfWeek
36+
from System.IO import FileAccess
37+
assert repr(DayOfWeek.Monday) == str(DayOfWeek.Monday) == "MONDAY"
38+
assert str([DayOfWeek.Monday, FileAccess.ReadWrite]) == "[MONDAY, READ_WRITE]"
39+
40+
def test_struct_without_tostring_override():
41+
"""Test struct not overriding ToString() keeps the default repr instead of ValueType's type name"""
42+
from System.Collections.Generic import List
43+
ob = List[int]().GetEnumerator()
44+
assert repr(ob).startswith("<System.Collections.Generic.List")
45+
assert " object at " in repr(ob)
46+
3347
def test_no_tostring_override():
3448
"""Test object not overriding ToString() keeps the default repr"""
3549
ob = System.Object()

0 commit comments

Comments
 (0)