Using __repr__ or __str__ for own printable class?

Alex Martelli aleax at aleax.it
Sat Apr 12 11:26:27 EDT 2003


Mads Orbesen Troest wrote:

> Hi Pythoners;
> 
> If I create a class which I want to be able to print like this ...
> tst = myclass()
> exp = r"test: %(intepol)s";
> print exp % { 'intepol':tst }
> 
> ... it seems I have two choices, either of which appear to work. I can
> overload the __str__ or the __repr__ method.
> 
> Which is the most correct to use; or should I even overload both? The

I've found that "both" is usually the answer -- if you define __repr__
and not __str__, all stringification of instances of your class uses the
__repr__ you defined, so that may suffice if there's only one way in
which you want such instances to be stringified.

> documentation says __str__ is for the, quote, informal representation;
> whereas __repr__ is for the, quote, official representation. Furthermore,

Yes, normally -- HOWEVER, unfortunately, when what you ask for an
"informal representation" of is a list, tuple or dict containing
instances of your class, it's your class's __repr__ -- NOT its
__str__ -- that ends up being used...:

>>> class Z:
...   def __str__(self): return 'nice!'
...
>>> print Z()
nice!
>>> print [Z()]
[<__main__.Z instance at 0x81c9e1c>]
>>>

> __reptr__ should, quote, look like an expresseion. I'm not quite sure what
> is meant by these distinctions. Is it that __repr__ is used by pickle and
> the like, and - thus - should represent the entire object state? Given

Not used by pickle, but ideally it should indeed represent the entire
object state -- eval(repr(x))==x is the goal, though it's not always
feasible to get anywhere near it (while remaining somewhat redable to a
programmerexamining the repr-stringified object).

> that I simply want to determine what should happen when one tries to print
> an instance, do I assume correctly when I gather that __str__ would be the
> more appropriate of the two - or is there some other way I should achieve
> this?

If you only care about print myclass() and not about print [myclass()], then
yes, __str__ suffices.  If you find yourself often printing lists, tuples
and dicts containing instances of your class, then __repr__ too will often
end up being used, so you may want to define both (or just __repr__, since
if __str__ isn't defined then print myclass() will use myclass.__repr__).


Alex





More information about the Python-list mailing list