__str__ vs. __repr__

Donn Cave donn at u.washington.edu
Tue Nov 2 12:48:56 EST 1999

Quoth Randall Hopper <aa8vb at yahoo.com>:
| Thanks.  That's the source of my confusion.  I wanted to follow the
| language convention.  But Python's internals currently don't follow it, so
| the point is somewhat moot.
| For consistency, would it make sense to change this for Python 1.5.3 (that
| is, have sequence and dict types pass 'str-vs-repr'ness down)?

I'd go back to an earlier followup on this and try to refine the
critical point, why __str__?  The man said __str__ is intended to
be ``friendly''.

I think it might help to be a little more specific about whose friend
this string is.  For me, anyway, __str__ is for an object whose data
model supports a string value.  For example, if we toss a TypeError
exception value into a context where a string is expected, it might
act like a string 'illegal argument type for built-in operation'.
This isn't just an abridged representation.  In a sense it doesn't
represent the object at all directly, but rather allows the object
to substitute a data value that the programmer expects will be useful,
based on some insight into the meaning of the object and its data
in some context.  In this context, that string value is friendly, but
in any other context, it's deceptive and inappropriate.  In the
distribution library, you'll find lots of __repr__ methods and
relatively few __str__ methods, I guess because it's relatively
unusual to find a string value that's really friendly in a broad
enough context for a library class.

Now there is no such accounting for the context in which sequences
and dicts will be used, they're used everywhere.  The string value
of these objects should directly represent them as the kind of objects
they are, and I think it follows that in this context their contents
should be rendered in the same literal way - to substitute __str__
values instead would only compromise that representation.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu

More information about the Python-list mailing list