confused about __str__ vs. __repr__

Mel mwilson at the-wire.com
Thu Dec 18 17:57:08 CET 2008


Neal Becker wrote:

> Tino Wildenhain wrote:
> 
>> Neal Becker wrote:
>>> Reading some FAQ, I see that __str__ is "meant for human eyes".
>>> 
>>> But it seems that:
>>> class X(object):
>>>     def __str__(self):
>>>         return "str"
>>>     def __repr__(self):
>>>         return "repr"
>>> 
>>> x = X()
>>> d = {0 : x}
>>> print d
>>> {0: repr}
>>> 
>>> 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.

Basically because there are too many right ways to format the resulting
report.  Space separated?  Tab separated?  One per line?  Boxes around
them?  As HTML definition lists?  Creating a standard report form would
take a lot of work and wouldn't, finally, solve very many peoples'
problems.

        Mel.




More information about the Python-list mailing list