str() for containers

John Roth newsgroups at jhrothjr.com
Sat Jun 19 08:41:56 EDT 2004


"George Sakkis" <gsakkis at rutgers.edu> wrote in message
news:40d07ac6 at rutgers.edu...
> Hi all,
>
> I find the string representation behaviour of builtin containers
> (tuples,lists,dicts) unintuitive in that they don't call recursively str()
> on their contents (e.g. as in Java) :

> It's even more cumbersome for containers of containers (e.g. lists of
dicts,
> etc.). Of course one can (or should) encapsulate such stuctures in a class
> and define __str__ to behave as expected, but why not having it by default
?
> Is there a good reason for this ?

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

Human readable output from a container, however, needs
to be very clear on the distinction between the container
and the objects that are contained. It isn't always obvious
whether using str() or repr() on the contained object is the
best policy, and in some cases I suspect that something
different from either would be helpful.

The only clean solution I can see is to provide a third built-in
that provides the "right" output when a container class needs
to turn an object into a string. However, someone else
is going to have to do the work of writing up the use
cases and the PEP - I don't care enough.

John Roth
>
> George
>
>





More information about the Python-list mailing list