str() for containers

George Sakkis gsakkis at rutgers.edu
Wed Jun 16 12:52:22 EDT 2004


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

###########################################

>>> class A(object):
>>>     def __str__(self): return "a"
>>> print A()
a
>>> print [A()]
[<__main__.A object at 0xa1a5c6c>]
>>> print map(str,[A()])
['a']

###########################################

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 ?

George





More information about the Python-list mailing list