confused about __str__ vs. __repr__

rdmurray at bitdance.com rdmurray at bitdance.com
Thu Dec 18 11:14:31 EST 2008


Quoth "Diez B. Roggisch" <deets at nospam.web.de>:
> Neal Becker wrote:
> 
> > Tino Wildenhain wrote:
> > 
> >> Neal Becker wrote:
> >> ...
> >>> 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.

Note that this last is no longer true in Python 3.0.  There, repr prints
into the current encoding of the output, and so you may get decode errors.
This is an accepted usability tradeoff, as it allows people using these
character sets (and who therefore will have terminals set to display
them!) to actually see the characters in their data.  If you need the
old behavior you use 'ascii'.

--RDM




More information about the Python-list mailing list