Using __repr__ or __str__ for own printable class?

Erik Max Francis max at
Mon Apr 14 07:59:14 CEST 2003

"Greg Ewing (using" wrote:

> I don't find those guidelines particularly useful except
> in fairly special cases. More generally, the rule of thumb
> I use is that __str__ is for the "normal" output of the
> program, whatever that might be, whereas __repr__ is for
> debugging output.

Same here.  Usually I define __str__ to be something short and
meaningful, and __repr__ to be something like

	def __repr__(self):
	    return "<%s @ 0x%x (%s)>" % \
	           (self.__class__.__name__, id(self), str(self))

That way it helps to see things like:

>>> Course(lowEarthOrbit, lowMarsOrbit).transfers()
[<ExtractionTransfer @ 0x82893ac (out of `low orbit around `Earth'')>,
<HohmannTransfer @ 0x812cef4 (Hohmann from `Earth' to `Mars')>,
<InsertionTransfer @ 0x82adb64 (into `low orbit around `Mars'')>]

 Erik Max Francis / max at /
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Freedom is a road seldom travelled by the multitudes
\__/ Public Enemy
    ZOE /
 A simple Python OpenGL rendering engine.

More information about the Python-list mailing list