str(list)

  • Thread starter Trevor Blackwell
  • Start date
T

Trevor Blackwell

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>]
 
D

Donn Cave

Trevor Blackwell said:
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 -
[A, B]

You may find this acceptable, but who would put up with this?
[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, (e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,438
Messages
2,571,699
Members
48,796
Latest member
Greg L.
Top