[Python-3000] PEP 3138- String representation in Python 3000

Adam Olsen rhamph at gmail.com
Tue May 27 06:52:17 CEST 2008


On Mon, May 26, 2008 at 8:13 PM, Jim Jewett <jimjjewett at gmail.com> wrote:
> On 5/26/08, Adam Olsen <rhamph at gmail.com> wrote:
>> There's a reason for that convention. Would you prefer str(['1', '2',
>> '3']) return '[1, 2, 3]'?
>> I don't think anyone is arguing about how to display
>> >>> "%" % string
>> The problem is classes where str(x) != repr(x), and how they get
> messed up when a container holding (one of their) instances is
> printed.
>>>>> class A:
> def __str__(self): return "an A"
>>>> a=A()
>>>>> print a # this is fine.
> an A
>>>> str(a) # this is OK, you have asked for "%s" % a
> 'an A'
>>>> repr(a) # this is OK, you wanted repr explicitly.
> '<__main__.A instance at 0x012DDAF8>'
>>>>> print ([a]) # this stinks ...
> [<__main__.A instance at 0x012DDAF8>]
>> It would be much better as:
>>>>> print ([a]) # after fixing the recursion bug
> ['an a']
>>>> Whereas you are asking about the (perhaps also acceptable):
>>>>> # after fixing the recursion bug,
>>>> print ([a]) # and somehow not even applying str
> [an a]

Hmm, I see where the confusion is. Containers only define __repr__,
so although you think it's the list.__str__ that's mistakenly using
repr(), it's str(list) itself that's calling repr(list).
So the question to ask is whether we can define a useful __str__ for
containers. str(['an a']) -> '[an a]' is not too bad, but
str(['hello, world']) -> '[hello, world]' is ambiguous. It crosses
the line into garbage.
We could probably define a third variant (beside __str__ and __repr__)
which'd be "pretty but unambiguous", but if it's just for escaping
unicode you should use PEP 3138's ascii_repr(), and if it's for more
it should be a separate discussion on python-list/python-ideas instead
of here.
Along the way I've found a new definition of repr: unambiguous when
used in a container's repr.
-- 
Adam Olsen, aka Rhamphoryncus


More information about the Python-3000 mailing list

AltStyle によって変換されたページ (->オリジナル) /