[Python-3000] Recursive str
Oleg Broytmann
phd at phd.pp.ru
Thu Apr 17 11:14:10 CEST 2008
On Thu, Apr 17, 2008 at 01:36:54PM +1200, Greg Ewing wrote:
> Oleg Broytmann wrote:
> > Do I understand it right that str(objects) calls repr() on items to
> > properly quote strings? (str([1, '1']) must give "[1, '1']" as the result).
> > Is it the only reason?
>
> In the case of strings, yes. More generally, there
> can be any kind of object in the list, and repr(x)
> is more likely to give an unambiguous idea of what
> x is than str(x) when it's embedded in a comma-
> separated list.
When I use str(container) instead of repr(comtainer) does Python need to
guess if I want an unambiguous representation or a printable representation
of items? I don't think there is a room for guessing - I explicitly said
str().
> Python has no way of guessing the most appropriate
> way to display your list of objects when you use
> str(), so it doesn't try.
It doesn't need to guess - all objects *except strings* have __str__, so
it should just call it.
> You have to tell it by
> writing code to do what you want.
Well, I found the root of the problem. Python's builtin containers
(list, tuple, dict, set) implement __repr__ but not __str__ and of course
__repr__ calls repr() on items (which is the correct behaviour).
The current implementation goes like this:
class object:
def __str__(self): # In case the derived class doesn't implement it
return repr(self)
class list(object):
def __repr__(self)
pieces = []
for item in self:
pieces.append(repr(item))
return '[%s]' % (', '.join(pieces))
I'd like to see __str__ implemented the following way:
def __str__(self)
pieces = []
for item in self:
if isinstance(item, str):
pieces.append("'%s'" % item)
else:
pieces.append(str(item))
return '[%s]' % (', '.join(pieces))
Oleg.
--
Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru
Programmers don't die, they just GOSUB without RETURN.
More information about the Python-3000
mailing list