str() for containers

Donn Cave donn at drizzle.com
Sun Jun 20 00:57:43 EDT 2004


Quoth "John Roth" <newsgroups at jhrothjr.com>:
...
| I don't think there's a ***good*** reason. The root of
| the issue is that the str() / repr() distinction is too simplistic
| for containers. The output of str() is supposed to be human
| readable, and the output of repr() is supposed to be able
| to round-trip through exec/eval (which is not always possible,
| but should be maintained if it is.)

That's one way to look at it, but it's a perspective that will
always leave you dissatisfied with both str and repr.

Not only is repr-as-marshal not always possible, it's very widely
not implemented even when it could be, and anyone who relies on
this feature is asking for trouble.  Human readable is as vacuous
an expectation as there could be for what str does, so it's hard
to say for sure you'll be disappointed there, but then it's just
impossible to imagine any solid basis for saying whether a value
is going to be human readable.  I've seen what the documentation
says, and there has been plenty of discussion about this.

The way I see it, __str__ is about conversion to string data.  It
really applies to only those objects that can naturally be converted
to a string.  If lists had a __str__ function, then str(list) would
be the inverse of list(str), but since that would raise all kinds
of questions about what to do with lists containing other things
besides strings of length 1, there is no __str__ function.  Instead,
str(list) calls __repr__.

Repr renders the object as a string.  Not just the object's value
in a computational sense, so to speak, but the object implementation.
So it's typically more interesting to a programmer, than the program's
user.  That could be seen as a human readability issue, but it puts
the point into better perspective - what's the user-oriented value
of a list as string?  There isn't one.

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list