Using __repr__ or __str__ for own printable class?

Donn Cave donn at drizzle.com
Thu Apr 17 03:18:02 EDT 2003


Quoth Peter Hansen <peter at engcorp.com>:
| Steven Taschuk wrote:
...
|> 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.

Yes!  An object implements the __str__ interface to function as a
string in some computation that requires a string.

| 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__.  

Works for me.  Of course the documentation mentions repr's use
in debugging etc., but it's distinctly subordinated.  __repr__
must conform to the expression requirement if possible, and
in the __str__ documentation even that concession (``if possible'')
is omitted.

	Donn Cave, donn at drizzle.com




More information about the Python-list mailing list