On 5/27/08, Adam Olsen <[EMAIL PROTECTED]> wrote: > On Mon, May 26, 2008 at 8:13 PM, Jim Jewett <[EMAIL PROTECTED]> wrote:
> > 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'] > 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). Exactly. And the fact that it then calls repr (rather than str) on the contents -- even though the user asked for str -- is what I (but not Nick) consider a bug. I believe this bug is also the only real source of the pain that motivates PEP 3138. > 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. I would consider '["hello, world"]' to be perfectly acceptable; the conversion to str was explicit. But to be honest, I would also accept '[hello, world]' despite the ambiguity -- if ambiguity is a problem, then str probably isn't the right function. (Admittedly, that does increase the pressure for a 3rd case in between; I'm just not sure that there would be enough need for that in-between, if str worked "all the way down".) > Along the way I've found a new definition of repr: unambiguous when > used in a container's repr. err ... actually even that isn't met, if you look too hard at corner (or malicious) cases. But I agree that it is a good goal -- which need not apply to a containers __str__. -jJ _______________________________________________ Python-3000 mailing list Python-3000@python.org http://mail.python.org/mailman/listinfo/python-3000 Unsubscribe: http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com