Using __repr__ or __str__ for own printable class?
David Abrahams
dave at boost-consulting.com
Wed Apr 23 05:13:37 EDT 2003
"Donn Cave" <donn at drizzle.com> writes:
> 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.
One idea might be:
# pseudocode
class object:
def __repr__(self):
if hasattr(self, '__getinitargs__'):
return (
repr(self.__class__)
+ repr(self.__getinitargs__())
)
else:
return # whatever we do today
I know that would only handle a small class of types, since most
aren't picklable, but it might encourage people to implement
__getinitargs__ to get the right __repr__ behavior.
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Python-list
mailing list