Using __repr__ or __str__ for own printable class?

Donn Cave donn at drizzle.com
Wed Apr 23 01:21:50 EDT 2003


Quoth "Terry Reedy" <tjreedy at udel.edu>:
| "Ted Drain" <teddrain at earthlink.net> wrote in message
| news:f6a31cb8.0304220810.547f5acd at posting.google.com...
|> My $.02:
|>
|> We use Python as a scripting interface to an underlying C++ system.
|> The users write Python code to do what they want.  We ended up writing
|> __repr__ and __str__ in our classes to be the same thing because our
|> users were very annoyed when they typed:
|>
|> >>> s
|> >>> print s
|>
|> and got different results.
|
| If you think of repr(o) as the codewriter view of an object o and
| str(o) as the (passive) user view of o, then printing repr(o) in
| interactive (codewriter) mode makes perfect sense.

Coincidentally, today I was looking into a little Mailman problem.
Its subclass of Message defines __repr__ to return __str__().
Unfortunately, __str__ is a fairly involved function that not only
returns information that's completely inappropriate for situations
like the interpreter, it's also prone to failure with Unicode troubles.

So here's this object.  You can't repr() it, including implicitly
from the interpreter prompt - you get a traceback instead.  Of course
that also goes for the list object that contains this object.  To
me, this is not right, and maybe it ought to be another point to
consider if we're reconsidering the documentation for __repr__.
Wish I could specify this better, but I believe there's a minimalist
way to think about implementing __repr__ that will tend to make it
less interesting but more reliable.

	Donn Cave, donn at drizzle.com




More information about the Python-list mailing list