Using __repr__ or __str__ for own printable class?

Tim Peters tim_one at email.msn.com
Sat Apr 12 22:24:50 EDT 2003


[Alex Martelli]
> IMHO the most maddening use of __repr__ is that done by the
> implementation of __str__ for all built-in container types:
>
> >>> class X:
> ...   def __str__(self): return 'str'
> ...   def __repr__(self): return 'rep'
> ...
> >>> print [X()]
> [rep]
> >>>
>
> There's supposed to be a good reason for this to print [rep],
> rather than [str] as common sense would suggest, but I keep
> forgetting it (so it's probably nor very compelling;-).

It's the problem of what to do with contained strings.  If str(container)
applied str() to the containees, then, e.g.,

    print [2, "2", "[3, 4]"]

would display

    [2, 2, [3, 4]]

instead of today's

    [2, '2', '[3, 4]']

Many would find the former unbearably misleading, including Guido.  It would
likely be confusing whenever a string contained commas, colons, square
brackets, curly braces, or parentheses (the delimiter characters used by the
convert-to-string methods of the basic builtin containers).  OTOH, if
str(string) were changed to act like repr(string), then WYSIWYG would be
violated when printing strings directly.

So strings really seem to want three display gimmicks:  pump out the bytes
as-is to the display device (current str.__str__); produce a portable 7-bit
printable-ASCII encoding, with escape sequences as needed (current
str.__repr__); and pump out the bytes as-is, except with enough decoration
so that it can still be identified as a string when part of the display of a
container.  That last one is an ongoing sore point for people who can't use
7-bit ASCII to spell their name:  when their name appears in a container
(say, as a dict key), displaying the container converts the "funny
characters" in their name to backslash hex escapes.

OTOH, no type other than a string type seems to feel a pressing need for
more than two convert-to-string gimmicks, and the basic container types
don't even distinguish repr from str (str(list) and repr(list) act the same
today because they are the same today).

In any case, unless containers are to special-case the snot out of string
containees, their convert-to-string methods will apply str() or repr()
uniformly to all containees.  Because of the example above, they choose to
apply repr().  That problem with strings is really all there is to this
decision.






More information about the Python-list mailing list