Bad suggestion for changing __repr__ vs __str__ behavior

Tim Peters (tim@ksr.com)
Thu, 03 Feb 94 01:04:59 EST

After picking up 1.0.0, I took a whack at updating Demo/classes/Dates.py
to follow the new

str(x) should be pleasant to read

repr(x) should strive to achieve eval(repr(x)) == x

conventions.

So, e.g., a newly-fiddled version of Dates works like so:

>>> from Dates import *
>>> t = today()
>>> print str(t) # easy to read
Thu 3 Feb 1994
>>> print repr(t) # easy to eval
Date(2, 3, 1994)
>>> eval(`t`) == t
1
>>>

That's fine. The difficulty is that "str behavior" appears to be
shallow:

>>> todo = { t : 'send gripe to python-list' }
>>> todo # I expected this to be hard to read (implicit use of 'repr')
{Date(2, 3, 1994): 'send gripe to python-list'}
>>> str(todo) # but not this (explicit use of 'str')
"{Date(2, 3, 1994): 'send gripe to python-list'}"
>>> print todo # or this (implicit use of 'str')
{Date(2, 3, 1994): 'send gripe to python-list'}
>>>

That is, in 'str(some_structure)', it's actually repr that appears to get
used in the structure's (dict, tuple, list) guts. So there doesn't
appear to be a general way to get the (to me) much more readable

{'Thu 3 Feb 1994': 'send gripe to python-list'}

It seems Not Good if the "pleasant" version of object output can only be
gotten when an object is used in isolation -- agreed?

The obvious suggestion is that whichever of str or repr is applied at the
top level be used all the way to the leaves too.

But then I'm afraid str(todo) would actually yield

{Thu 3 Feb 1994: send gripe to python-list}

and the lack of internal quotes would make it hard to read again, but for
a different reason (picture a more elaborate todo dict, with string
entries that themselves contained colons and commas -- and/or suppose the
key representations did). Anyone see a clean way around that? I haven't,
short of special-casing strings. It's deliciously irritating!

yum-yum-slobber-ing-ly y'rs - tim

Tim Peters tim@ksr.com
not speaking for Kendall Square Research Corp