__str__ vs. __repr__

Tim Peters tim_one at email.msn.com
Tue Nov 2 06:05:30 CET 1999

[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...

It's too convoluted for my tastes!  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?  For that matter,
why is repr implied at an interactive prompt given a raw expression?  Seems
that friendly strings would be more appropriate there.  And why is there a
shorthand (`x`) for repr(x) but not for str(x)?

These are Great Mysteries debated even among the Ancient Ones.  If the
scheme didn't already exist, I don't think we'd have much luck arguing for
its adoption <wink>.

3/4ths-of-one-idea-plus-1/4th-of-another-adds-up-to-2/3rds-ly y'rs  - tim

More information about the Python-list mailing list