str(list) calls repr() on elements?

Tim Peters tim_one at email.msn.com
Thu Oct 19 00:18:19 EDT 2000


[Michael Dyck]
> It seems that the built-in function 'str', when applied to a list/tuple,
> constructs its result by calling 'repr' on the elements of the list/tuple,
> rather than 'str'. How come?

Historical accident, but hard to get away from.  All the builtin container
types (list, tuple, dict) use repr() on their containees, regardless of
whether str() or repr() was applied at the top level (in fact, the str() and
repr() methods for the builtin container types execute exactly the same
code -- they're "the same" methods).

I think that sucks (you can't truly appreciate why before you routinely
define your own __str__ and __repr__ methods in your own classes), but no
consensus on repairing it has yet been reached.  The primary reason today is
that repr(string) puts quotes around string, while str(string) cannot (for
various reasons it would be nuts if str(string) didn't return string
unchanged).  So, e.g., if str(list) "passed str() down", then

    str(["a", "b,", "c"])

would produce the string

    [a, b,, c]

instead of today's

    ['a', 'b,', 'c']

and str([42, "42"])

    [42, 42]

instead of today's

    [42, '42']

etc.  When making a string out of a container, you really want *some* way
for the fundamental builtin types to announce their nature in the string,
whether str() or repr() is applied at the top level.  "passing repr() down
regardless" satisfies that desire, but is almost certainly not what you
really want (and esp. not in the presence of your own __str__ and __repr__
methods).

Don't know whether this will ever improve.

everyone-complains-too-much-about-the-possible-hacks-out-ly y'rs  - tim







More information about the Python-list mailing list