Using __repr__ or __str__ for own printable class?

Peter Hansen peter at engcorp.com
Wed Apr 16 20:21:11 EDT 2003


Steven Taschuk wrote:
> 
> Quoth Donn Cave:
>   [...]
> > It's clear that the docs promote this idea, but they also hint at
> > its half-baked quality - repr() evals to the original value, unless
> > it doesn't.  I don't think the idea is clear at all.
> > [...] The only kind of clarity this documentation possesses is
> > when it lets you read into it what you already thought.  Not the fault
> > of the documentation, though, but of the unsound ideas behind it.
> 
> I'm of the opinion that the ideas are sound; if there is a
> problem, I think it must lie in the documentation.

There may also be some disagreement on appropriate uses, which could
be the cause of the documentation problem, or the result of it (or
neither :-).

> But information-rich and unambiguous representations, however
> useful for (e.g.) debugging, are not always easy to read or
> understand; for the humans then, we'd like an "informal",
> easier-to-read representation, whence __str__.

I've always considered __str__ to be for use in the application,
such as when you have a class which is sometimes asked for a 
string representation for display purposes to a real user, or in
an application log, or something.

I've always considered __repr__ to be for use in *debugging* the
application, where a *debugging* log needs to display information,
or in a traceback.  Since it's next to impossible for most interesting
objects to be reproduced easily from the output of __repr__ if it's
also desirable that the output be meaningful and useful to a human 
reader, I don't buy into the 'eval(repr(x)) == x' theory very much,
other than to note that it's the most obvious thing to do for 
primitive data types.

I've never had any confusion in my own mind about when it's 
appropriate to use one or the other.  Perhaps this perspective 
should be used in the documentation, rather than the focus on 
reproducing objects from their __repr__.  

-and-not-just-because-it's-my-own-view-ly y'rs, ;-)
 Peter




More information about the Python-list mailing list