classification
Title: Allow printing of str-derived classes
Type: behavior Stage:
Components: Library (Lib) Versions: Python 2.6
process
Status: closed Resolution: works for me
Dependencies: Superseder:
Assigned To: Nosy List: Arfrever, Radu.Dan, benjamin.peterson
Priority: normal Keywords:

Created on 2012-10-08 16:58 by Radu.Dan, last changed 2012-10-08 20:15 by Arfrever. This issue is now closed.

Messages (4)
msg172396 - (view) Author: Radu Dan (Radu.Dan) Date: 2012-10-08 16:58
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 <module>
    print a
RuntimeError: print recursion

Given that instances of 'str' are immutable, I see no reason why this should not work.
msg172407 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2012-10-08 20:01
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'>
msg172408 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2012-10-08 20:02
And indeed

>>> print(a)
hello world
msg172409 - (view) Author: Arfrever Frehtes Taifersar Arahesis (Arfrever) * (Python triager) Date: 2012-10-08 20:15
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
2012-10-08 20:15:21Arfreversetresolution: not a bug -> works for me

messages: + msg172409
nosy: + Arfrever
2012-10-08 20:02:55benjamin.petersonsetmessages: + msg172408
2012-10-08 20:01:22benjamin.petersonsetstatus: open -> closed

nosy: + benjamin.peterson
messages: + msg172407

resolution: not a bug
2012-10-08 16:58:20Radu.Dancreate