Using __repr__ or __str__ for own printable class?

Alex Martelli aleax at
Sat Apr 12 17:11:44 CEST 2003

Steven Taschuk wrote:
> Pickle doesn't use __repr__; it has other, more reliable, ways of
> getting object state.


> __repr__ is used by: (1) '%r' % foo and repr(foo); (2) '%s' % foo,
> str(foo), and print foo if __str__ isn't provided; and (3) the
> interactive interpreter, when printing the value of an expression
> entered at the prompt.  (And no doubt, other places that I've
> forgotten.)

IMHO the most maddening use of __repr__ is that done by the 
implementation of __str__ for all built-in container types:

>>> class X:
...   def __str__(self): return 'str'
...   def __repr__(self): return 'rep'
>>> print [X()]

There's supposed to be a good reason for this to print [rep],
rather than [str] as common sense would suggest, but I keep
forgetting it (so it's probably nor very compelling;-).


More information about the Python-list mailing list