print and str subclass with tab in value

D

David Bolen

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
'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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,785
Messages
2,569,624
Members
45,318
Latest member
LuisWestma

Latest Threads

Top