__str__ vs. __repr__

Michael Hudson mwh21 at cam.ac.uk
Mon Nov 1 22:24:12 CET 1999


Gerrit Holl <gerrit.holl at pobox.com> writes:

> Randall Hopper wrote:
> > 
> > 1) Is there a convention for what __str__ and __repr__ should return for
> >    classes?
> 
> __str__ should return a string, __repr__ may also return, for example, a
> dictionairy.

Ehh? No, I don't think so:

>>> class Class:
...  def __repr__(self):
...   return {}
...
>>> Class()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: repr not string

>From the reference manual (which I could paraphrase, but there'd be no
real point):

   __repr__ (self)
          Called by the repr() built-in function and by string
          conversions (reverse quotes) to compute the ``official'' string
          representation of an object. This should normally look like a
          valid Python expression that can be used to recreate an object
          with the same value. By convention, objects which cannot be
          trivially converted to strings which can be used to create a
          similar object produce a string of the form "<...some useful
          description...>".

   __str__ (self)
          Called by the str() built-in function and by the print
          statement to compute the ``informal'' string representation of
          an object. This differs from __repr__() in that it does not
          have to be a valid Python expression: a more convenient or
          concise representation may be used instead.
 
The idea is that 

eval(repr(x)) == x

should be true as much as is possible, whereas 

str(x)

should be fit for human consumption.

> > 2) Or, whatever they return, should they return the same value?

It's worth noting that the *only* type I know of that has a different
`str' to its `repr' is the string type:

>>> print str("hello")
hello
>>> print repr("hello")
'hello'

Regards,
Michael




More information about the Python-list mailing list