Classes that extend the builtin 'str' cannot be printed as is, and are automatically converted to string. #!/bin/env python class newstring(str): def __str__(self): return self a = newstring("hello world") print a Running this returns: Traceback (most recent call last): File "./test.py", line 7, in print a RuntimeError: print recursion Given that instances of 'str' are immutable, I see no reason why this should not work.
Python 3.4.0a0 (default:8f048c8c855e, Oct 8 2012, 13:46:48) [GCC 4.5.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> class newstring(str): ... def __str__(self): ... return self ... >>> type(str(newstring())) <class '__main__.newstring'>
Radu Dan: Printing of str-derived classes works in Python >=3.0, so you should just upgrade to newer version of Python. New features will not be backported to Python 2.
History
Date
User
Action
Args
2022-04-11 14:57:37
admin
set
github: 60371
2012-10-08 20:15:21
Arfrever
set
resolution: not a bug -> works for memessages: + nosy: + Arfrever
2012-10-08 20:02:55
benjamin.peterson
set
messages: +
2012-10-08 20:01:22
benjamin.peterson
set
status: open -> closednosy: + benjamin.petersonmessages: + resolution: not a bug