Using __repr__ or __str__ for own printable class?

Donn Cave donn at drizzle.com
Tue Apr 15 03:01:04 EDT 2003


Quoth Mads Orbesen Troest <mads at troest.NEVERMORE.dk>:
| ... That was what I was after in the first place, and it seemed like the 
| way to do it is to override the __str__ method. I would like to be able to 
| do this ...
| 	print someInstanceOfMyClass
|
| ... and then determine what should be printed. This works with __str__ but 
| I was/am afraid if this overriding of __str__ will conflict with other uses 
| of __str__ and/or __repr__.

As you have seen, there is some confusion over the principles.

I personally think the simplest and most useful way to look at it is

  __str__: your object's data as a string

  __repr__: your object as a string.

(The object's data may be generated during __str__, for example
random gibberish, contents of a file, whatever.  My point is that
one calls str() to get those file contents, random gibberish or
whatever, while one calls repr() to get information about the
object and not strictly about the data.)

For most objects they're the same, because there isn't any obvious
and distinct value of __str__.  For a string, clearly if you make
a string from its data, you've got the same string, so str(a) = a.
However the object as a string carries quotes to identify itself.
repr(instance of A) != repr(instance of B) - even if they contain
the same data, they are different as objects.

The idea that repr() must marshal the object is a sorely misguided
extension of this.  It is not consistently supported enough to be
clearly useful, and it has done some harm, e.g., it apparently
contributed to a move to make the repr for floats to display full
precision.  That behavior in turn seems to be responsible for a good
deal of the complaining over why str(list) has to use repr on its
items.

	Donn Cave, donn at drizzle.com




More information about the Python-list mailing list