str(list) calls repr() on elements?

Huaiyu Zhu hzhu at users.sourceforge.net
Thu Oct 19 15:21:38 EDT 2000


On Wed, 18 Oct 2000 08:04:31 GMT, Michael Dyck <MichaelDyck at home.com> wrote:
>It seems that the built-in function 'str', when applied to a list/tuple,
>constructs its result by calling 'repr' on the elements of the list/tuple,
>rather than 'str'. How come?
>
>e.g.
>>> str(1L)
>'1'
>>> repr(1L)
>'1L'
>>> str( [1L] )
>'[1L]'  # not '[1]'
>
>-Michael Dyck

The way I work around this problem is as follows, and I'm interested in any
better solution.

Suppose you use containers to build a multilayer structure.  Use UserList
and UserDict in place of [] and {}.  Define methods, say myrepr, that are
distributed to the elements unchanged.  You need to make sure that at the
leaves of the structure they call str or repr as appropriate. This works,
but it is quite some work.

Another solution is to wrap all the possible elements in classes that
redefine __repr__, but that appears to be even more work and may be a
performance burden.

As Tim said, you can't just redefine __str__ in UserList as that will
confuse int with string due to str("12")==str(12).

Huaiyu





More information about the Python-list mailing list