print and str subclass with tab in value

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • David Bolen

    #1

    print and str subclass with tab in value

    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
    [color=blue][color=green][color=darkred]
    >>> x = strtest.mystr(' foo')
    >>> print x,1[/color][/color][/color]
    Test 1[color=blue][color=green][color=darkred]
    >>> print repr(x),1[/color][/color][/color]
    'foo' 1[color=blue][color=green][color=darkred]
    >>> x = strtest.mystr(' foo\t')
    >>> print x,1[/color][/color][/color]
    Test1[color=blue][color=green][color=darkred]
    >>> print repr(x),1[/color][/color][/color]
    '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.
    [color=blue][color=green][color=darkred]
    >>> x = 'testing\t'
    >>> print x,1[/color][/color][/color]
    testing[TAB]1[color=blue][color=green][color=darkred]
    >>> x = str('testing\t' )
    >>> print x,1[/color][/color][/color]
    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
Working...