This project has moved. For the latest updates, please go here.
2

Closed

ToString should call __str__, and other issues with __str__

description

Problem 1

 
Looks like ToString is not hooked up to str. It should be
 
class MyClass(object):
... def __str__(self):
... return "str result"
o = MyClass()

Use Reflection to simulate a call from another .NET language

o.GetType().GetMethod("ToString").Invoke(o, None) # Expected: this should call str but it does not
'IronPython.NewTypes.System.Object_...'
 

Problem 2

 
In the reverse direction, str is hooked up to ToString, but calling str(o) does not seem to call str.
 
class MyClass(object):
... def ToString(self):
... return "ToString implemented in Python"
o = MyClass()
o.__str__()
'ToString implemented in Python'
str(o) # Expected: should be the same output as calling str, but it is not
'<MyClass object at ...>'
 

Problem 3

 
Similar to Problem 1 but slightly different
 
class MyClass(object):
... pass
o = MyClass()
str(o) #
'<MyClass object at ...>'
o._str__() # Expected: Same output as calling str(o)
'IronPython.NewTypes.System.Object
...'
Closed Dec 9, 2014 at 7:55 PM by jdhardy
Migrated to GitHub.

comments

markhirota wrote Apr 13, 2011 at 4:47 PM

I would suggest the following for handling .NET objects that override ToString() -- a change from what is currently listed (http://www.ironpython.net/documentation/dotnet/dotnet.html#repr-str-on-net-objects)

".NET types which do override ToString, IronPython include a truncated (for display reasons) result of ToString in repr, and maps ToString directly to str:"

In this way, the repr will show -- up to some limit -- the ToString() when under interactive usage or the user invokes repr() on it -- and will display the full ToString() -- which could potentially be large -- when user invokes print() or str() on it.

wrote Apr 19, 2011 at 7:51 AM

wrote Nov 3, 2011 at 5:12 AM

wrote Mar 4, 2012 at 10:07 AM

wrote Feb 22, 2013 at 1:11 AM

wrote Dec 9, 2014 at 7:55 PM