print and str subclass with tab in value

David Bolen db3l at fitlinxx.com
Wed Feb 23 10:52:53 EST 2005


I ran into this strange behavior when noticing some missing spaces in
some debugging output.  It seems that somewhere in the print
processing, there is special handling for string contents that isn't
affected by changing how a string is represented when printed
(overriding __str__).

For example, given a class like:

    class mystr(str):

        def __new__(cls, value):
            return str.__new__(cls, value)

        def __str__(self):
            return 'Test'

you get the following behavior

>>> x = strtest.mystr('foo')
>>> print x,1
Test 1
>>> print repr(x),1
'foo' 1
>>> x = strtest.mystr('foo\t')
>>> print x,1
Test1
>>> print repr(x),1
'foo\t' 1

Note the lack of a space if the string value ends in a tab, even if
that tab has nothing to do with the printed representation of a
string.

It looks like it's part of basic string output since with a plain old
string literal the tab gets output (I've replaced the literal tab with
[TAB] in the output below) but no following string.

>>> x = 'testing\t'
>>> print x,1
testing[TAB]1
>>> x = str('testing\t')
>>> print x,1
testing[TAB]1

so I'm guessing it's part of some optimization of tab handling in
print output, although a quick perusal of the Python source didn't
have anything jump out at me.

It seems to me that this is probably a buglet since I would expect
print and its softspace handling to depend on what was actually
written and not internal values - has anyone else ever run into this.

-- David



More information about the Python-list mailing list