str behaviour

Tim Peters tim.one at home.com
Thu Mar 1 16:32:35 EST 2001


[Igor V. Rafienko]
> I was playing around with printing tuples, when I noticed how str
> behaves with "compound" types (such as tuples):
>
>
> >>> class A:
> ...     def __str__( self ):
> ...         return "I'm A"
> ...
> >>> a = A()
> >>> t = ( A, a )
> >>> str( t )
> '(<class __main__.A at 80fd498>, <__main__.A instance at 810f090>)'
> >>> str( a )
> "I'm A"
> >>>
>
>
> I expected str to be called recursively for the constituent types.
> But, alas, that did not happen. Am I misunderstanding something or is
> it the intended behaviour? If the latter is the case, could someone
> elaborate on why this behaviour was chosen?

You're on the edge of a very deep pit.  The builtin container types (lists,
tuples, dicts) "pass repr down" regardless of whether str() or repr() is
applied at the top level.  I've been whining about that for years myself
<wink>.

The primary reason is maddeningly simple:  it's for the benefit of contained
strings.  If str() "got passed down", then, e.g.,

    d = {"colon": ":", "comma": ",", "' greeting": "I'm A"}
    print d  # note that print implicitly applies str()

would print

   {' greeting: I'm A, comma: ,, colon: :}

instead of today's

   {"' greeting": "I'm A", 'comma': ',', 'colon': ':'}

so it would be an unreadable mess.

I call it "maddening" because, to date, nobody has thought of an alternative
that doesn't suck just as bad in one respect or another.  If DejaNews were
still useful, searching for ssctsoos ("str special casing the snot out of
strings") would yield more blather on the topic than you could tolerate.

Like most other issues involving repr-vs-str, it doesn't often bite so long
as you stick to the builtin types.  But once you write classes that implement
their own notions of __str__ and __repr__, it seems that more often than not
*neither* of them does what you want when instances end up in builtin
containers.

Good topic for a PEP!  Alas, that requires dreaming up a rational solution
first ...





More information about the Python-list mailing list