__str__ vs. __repr__

Guido van Rossum guido at cnri.reston.va.us
Tue Nov 2 08:47:17 EST 1999


Randall Hopper <aa8vb at yahoo.com> writes:

> Tim Peters:
>  |The real illness is that lists (and dicts, and tuples) don't pass
>  |str-vs-repr'ness *down*.  That is, even though the example explicitly
>  |asks for str of a list, the list object asks for the repr of its
>  |elements.  That's convoluted: if (as happens to be true) str is meant to
>  |give a friendly string, why do the builtin container types ask their
>  |containees to produce unfriendly strings regardless? 
> 
> 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.

Actually, Python's internals *do* follow the convention.  Dicts and
lists don't define __str__(), so str() for them defaults to
__repr__(), and then of course repr() is used for the items.  It may
be confusing, it may not be what you want, but it *is* consistent ;-(

> 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)?

This has been asked a few times before (and usually it's been reported
as a bug, which it isn't -- see above).  I happened to see this post
and it made me delve deep into my intuition trying to figure out why I
don't like propagating str() down container items.

Here's what I think it is.  There's no reason why an object's str()
should be particularly suited to being included in list syntax.  For
example, I could have a list containing the following items:

	1		# an integer
	'1'		# a string (of an integer literal)
	'2, 3'		# a string containing a comma and a space
	'], ['		# a string containing list delimiters

Under the proposed rules, this list would print as:

	[1, 1, 2, 3], []

I would find this confusing and I worry that it could be used to fool
the user.

--Guido van Rossum (home page: http://www.python.org/~guido/)




More information about the Python-list mailing list