__str__ vs. __repr__

Gordon McMillan gmcm at hypernet.com
Mon Nov 1 21:40:01 CET 1999


Randall Hopper wrote:

> 1) Is there a convention for what __str__ and __repr__ should
> return for
>    classes?
> 2) Or, whatever they return, should they return the same value?
> 3) If so, why have both in the language?

If possible, __repr__ should return something that when eval'd 
yields an identical object. If that's not possible, it should be 
the programmer's view of the object.

__str__ is free to return a highly munged user-friendly string. 
str(obj) will use obj.__repr__ if obj.__str__ doesn't exist.

Consider this:

class HTMLTable:
   blah blah blah

t = HTMLTable(...)
repr(t) # -> "MyModule.HTMLTable([...])"
str(t) # -> "<TABLE><TR>....."

(see IPWP for this idea carried to extreme lengths).

>      Searching the archives yields an example with odd behavior
>      that
> suggests they should generally return the same value:
> 
>    class c:
>        def __str__(self):  return 'foo'
>        def __repr__(self): return 'bar'
> 
>    >>> str(c())
>    'foo'
> 
>    >>> str([c(), c(), c()])
>    '[bar, bar, bar]'

Sick enough, but not convoluted enough, to be a Tim-ism...

- Gordon




More information about the Python-list mailing list