confused about __str__ vs. __repr__

Jean-Paul Calderone exarkun at divmod.com
Thu Dec 18 16:10:54 CET 2008


On Thu, 18 Dec 2008 09:51:01 -0500, Neal Becker <ndbecker2 at gmail.com> wrote:
>Tino Wildenhain wrote:
>
>> Neal Becker wrote:
>> ...
>>>>> So if __str__ is "meant for human eyes", then why isn't print using it!
>>>> it is:
>>>>
>>>>  > print x
>>>> str
>>>>
>>>> but dict just uses repr() for all its childs to print.
>>>>
>>>> T.
>>> That makes no sense to me.  If I call 'print' on a container, why
>>> wouldn't it recursively  print on the contained objects?  Since print
>>> means call str, printing a container should recursively call str on the
>>> objects.
>>
>> Every class is free on how to best implement __str__, you will find
>> the same behavior on tuple and list as well.
>>
>> Maybe its discussable to change the implementation sensibly, best if you
>> would come with a proposal? Perhaps pprint.pprint is a starting point?
>>
>> Regards
>> Tino
>
>First, I'd like to know if there is a rationale for the current design.  Am I correct in thinking this is a defect?

There is a rationale.  Consider:

    >>> class strit(object):
    ...     def __init__(self, it):
    ...             self.it = it
    ...     def __repr__(self):
    ...             return str(self.it)
    ... 

This will let us see what a dict.__str__ which called __str__ on the objects
in it would look like.  So first, something simple:

    >>> print str({strit("['foo']"): 'bar'})
    {['foo']: 'bar'}
    >>> 

Mildly confusing - you can't use a list as a dict key!  But it could be
worse:

    >>> print str({strit("1: 2, 3"): 'bar'})
    {1: 2, 3: 'bar'}
    >>> 

Wait - *how* many items are in that dictionary?

Hopefully that makes the rationale clear - when a human is looking at the
str of a dict (and a human is ostensibly the intended audience) - using
the __repr__ of the contained objects makes it easier for the human to
understand what's in the dict.  Using __str__ would make it much harder
in many cases.

Jean-Paul



More information about the Python-list mailing list