confused about __str__ vs. __repr__

Diez B. Roggisch deets at nospam.web.de
Thu Dec 18 10:53:08 EST 2008


Neal Becker wrote:

> Diez B. Roggisch wrote:
> 
>> Neal Becker 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?
>> 
>> I don't think so. First of all, there is no "generic" way of printing a
>> collection. And the current implementation tries to give an overview what
>> is contained in the collection, without trying to make it "fancy" - any
>> such thing needed to be hand-coded anyway.
>> 
>> Using repr for that is better suited, as for example string keys are
>> printed with quotes around them - making clear what they are, and not
>> irritating the user through potentially contained spaces or even things
>> that look as if they are python objects.
>> 
>> For example, if repr *wasn't* used,
>> 
>> { "{foo=bar}" : "baz"}
>> 
>> would be printed
>> 
>> {{foo=bar} : baz}
>> 
>> Which is *not* what the dictionary actually contains!
>> 
>> The same goes for unicode-objects. They appear with their "funny"
>> characters as \xXX-codes - instead of bailing out on you with
>> unicode-errors.
>> 
>> So, IMHO the current behavior is desired.
>> 
> 
> So if I want to overload something in my custom class, so that I get a
> nice string whether it's printed directly, or as part of a container, what
> is the recommendation?  Overload both __str__ and __repr__?

Yep. And it's easy enough if you don't care about them being different..

def __repr__(self):
    return str(self)


BTW, you newsreader still produces bogus follow-ups, which makes replying to
you unnerving.

Diez



More information about the Python-list mailing list