FAQ: __str__ vs __repr__

Terry Hancock hancock at anansispaceworks.com
Wed Jun 15 14:40:27 EDT 2005


On Wednesday 15 June 2005 08:06 am, Sébastien Boisgérault wrote:
> Jan Danielsson a écrit :
> >    However, I don't understand what __repr__ should be.
> It is an *exact* (if possible) description of the object's content,
> nicely packaged into a string.

However, this is often not the case. Frequently __repr__ will
return something like this:

>>> import re
>>> r = re.compile('\w+\d*')
>>> r
<_sre.SRE_Pattern object at 0x401a89b0>
>>> str(r)
'<_sre.SRE_Pattern object at 0x401a89b0>'
>>> repr(r)
'<_sre.SRE_Pattern object at 0x401a89b0>'

So don't obsess over it.  For many objects it isn't worth
the trouble, and for others, str() and repr() are sensibly the
same thing, but for some, the distinction is useful. That's
all.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list