str(list)

Donn Cave donn at u.washington.edu
Wed Jun 9 18:18:06 EDT 2004


In article <mailman.769.1086813776.6949.python-list at python.org>,
 Trevor Blackwell <tlb at anybots.com> wrote:

> I wish that str of a list would call str on the elements, rather than
> repr. Currently, list has only a repr function so it ends up calling
> repr on its members.
> 
> The way to fix this would be to add a list_str in Objects/listobject.c
> similar to list_repr.
> 
> An example:
> 
> class mytype:
>     def __init__(self, x):
>         self.x=x
> 
>     def __str__(self):
>         return "mytype(%s)" % self.x
> 
> foo=mytype("foo")
> bar=mytype("bar")
> 
> print foo # Prints mytype(foo)
> print bar # Prints mytype(bar)
> print [foo,bar]	# Prints [<__main__.mytype instance at 0x81b21ac>,
> 		# <__main__.mytype instance at 0x81b216c>]

You're not the first person to want this, but usually
it's because of the repr botch with floats.  I think
in your case the answer could be for the classes to
define a more suitable __repr__ method.

I'm sure I'm forgetting one or more problems with the
solution you propose, but the first one that comes to
mind is that __str__ commonly returns values that would
be confusing in this context.  Suppose you print strings -

  >>> print ['A', 'B']
  [A, B]

You may find this acceptable, but who would put up with this?

  >>> print ['A, B', 'C']
  [A, B, C]

Lists do not really have an appropriate str value - there
is no natural transformation of a list into a string value.
If there is, it's something like  ['A', 'B'] -> 'AB'.  The
brackets and commas are a notational thing that only makes
sense in repr.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list