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


ToString should call __str__, and other issues with __str__


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

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()
'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)
Closed Dec 9, 2014 at 8:55 PM by jdhardy
Migrated to GitHub.


markhirota wrote Apr 13, 2011 at 5:47 PM

I would suggest the following for handling .NET objects that override ToString() -- a change from what is currently listed (

".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 8:51 AM

wrote Nov 3, 2011 at 6:12 AM

wrote Mar 4, 2012 at 11:07 AM

wrote Feb 22, 2013 at 2:11 AM

wrote Dec 9, 2014 at 8:55 PM