FAQ: __str__ vs __repr__
Dave Benjamin
ramen at lackingtalent.com
Wed Jun 15 15:52:33 EDT 2005
Jan Danielsson wrote:
> Sorry, but I Just Don't Get It. I did search the 'net, I did read the
> FAQ, but I'm too dumb to understand.
Say we define a string "s" as follows:
>>> s = 'hello'
If we print "s", we see its string form (__str__):
>>> print s
hello
However, if we just examine "s", we see its representation (__repr__):
>>> s
'hello'
This can be verified by calling str() and repr() on the string:
>>> str(s)
'hello'
>>> repr(s)
"'hello'"
So, the result of repr() includes quotes, whereas the result of str()
does not. This has useful properties when the object is part of a more
complex structure. For instance, these two expressions print out the same:
>>> [s, s]
['hello', 'hello']
>>> print [s, s]
['hello', 'hello']
That's because, in either case, the repr() form is used. If Python only
had str(), we would probably expect str(s) = s, so we'd instead see
something like this imaginary snippet:
>>> [s, s]
[hello, hello]
>>> repr([s, s])
'[hello, hello]'
So, the convention in Python is that repr() returns a string that, when
evaluated, returns the original object. This is not always easy or
possible to do, but if you can do it, your objects will print nicely
when nested within Python's built-in data structures. Python's actual
behavior is this:
>>> repr([s, s])
"['hello', 'hello']"
And therefore:
>>> eval(repr([s, s]))
['hello', 'hello']
Also worth noting is that if you define __repr__, the default behavior
of __str__ is to delegate to that definition, so if you only want to
define one, it's often more convenient to just define __repr__.
Dave
More information about the Python-list
mailing list