__str__ vs. __repr__

Randall Hopper aa8vb at yahoo.com
Tue Nov 2 13:34:22 CET 1999

Tim Peters:
 |[Randall Hopper gives an example]
 |>    class c:
 |>        def __str__(self):  return 'foo'
 |>        def __repr__(self): return 'bar'
 |>    >>> str(c())
 |>    'foo'
 |>    >>> str([c(), c(), c()])
 |>    '[bar, bar, bar]'
 |[which Gordon McMillan explains, adding]
 |> Sick enough, but not convoluted enough, to be a Tim-ism...
 |The real illness is that lists (and dicts, and tuples) don't pass
 |str-vs-repr'ness *down*.  That is, even though the example explicitly
 |asks for str of a list, the list object asks for the repr of its
 |elements.  That's convoluted: if (as happens to be true) str is meant to
 |give a friendly string, why do the builtin container types ask their
 |containees to produce unfriendly strings regardless? 

Thanks.  That's the source of my confusion.  I wanted to follow the
language convention.  But Python's internals currently don't follow it, so
the point is somewhat moot.

For consistency, would it make sense to change this for Python 1.5.3 (that
is, have sequence and dict types pass 'str-vs-repr'ness down)?



Randall Hopper
aa8vb at yahoo.com

More information about the Python-list mailing list