printing a sequence...

Peter Otten __peter__ at web.de
Fri Jul 16 12:08:02 EDT 2004


Christopher T King wrote:

> On Fri, 16 Jul 2004, Peter Otten wrote:
> 
>> Peter Otten wrote:
>> 
>> > Florian Preknya wrote:
>> 
>> >> What I want to obtain is [value: 10, value: 12, value: 2].
>> 
>> >> Can I write somehow the print statement to force calling the A.__str__
>> >> function?
>> > 
>> > print [str(item) for item in a]
>> 
>> print "[%s]" % ", ".join(map(str, a))
> 
> I had the same problem with the same solution, and it makes me wonder, why
> does a list's __str__() method call the __repr__() method of its members?
> Personally, I think the __str__() call should be propagated, not turned
> into a __repr__() call.  I can't think of any instances in which such
> behavior is what you want (if the __repr__() of the members is wanted,
> then __repr__() should be used).

I didn't find it in the FAQ; I think the argument goes that the results of
propagating str() are sometimes misleading, e. g:

>>> class List(list):
...     def __str__(self):
...             return "[%s]" % ", ".join(map(str, self))
...
>>> List(["a", "b, c", "d"])
['a', 'b, c', 'd']
>>> print List(["a", "b, c", "d"])
[a, b, c, d]
>>>

OK, there may be subtler examples. Personally, I would prefer the above
problem over the current inconsistency.

While I'm at it, here's another alternative for the OP that handles nested
lists nicely:

>>> class D:
...     def __init__(self, value):
...             self.value = value
...     def __repr__(self):
...             if isinstance(self.value, list):
...                     return str(map(D, self.value))
...             else:
...                     return str(self.value)
...
>>> print D(["a", "b", "c"])
[a, b, c]
>>> print D(["a", "b", ["c", "d"]])
[a, b, [c, d]]
>>>

Peter




More information about the Python-list mailing list