[Tutor] __str__ vs. sys.displayhook
Steven D'Aprano
steve at pearwood.info
Sun Mar 20 19:53:35 EDT 2016
On Sun, Mar 20, 2016 at 07:57:55PM +0000, Albert-Jan Roskam wrote:
> > The intention is that repr() returns the "string representation" of the
> > object ("what does it look like?") while str() "converts this object to
> > a string". They are usually the same, but not always:
> >
> > py> from fractions import Fraction
> > py> x = Fraction(1, 2)
> > py> print(str(x))
> > 1/2
> > py> print(repr(x))
> > Fraction(1, 2)
>
> That makes sense to me. I read somewhere [1, 2]) that __repr__, when
> implemented and when possible, should return an eval-able
> representation of the object (though this is not enforce/checked).
This is considered a "nice to have" feature of repr(), but it shouldn't
be considered compulsory. It is mostly true for the more common
built-ins such as None, ints, floats, strings, lists etc. It's *not*
true for classes and functions, or anything using the default object
repr:
py> o = object()
py> repr(o)
'<object object at 0xb7d58188>'
> Or
> as somebody put it: __str__ is about readability, and __repr__ is
> about eval-ability: eval(repr(obj)) == obj, e.g.
I'd be cautious about putting so much emphasis on the eval part, but
it's broadly correct. For many objects, the two will be the same, and
for some objects it is impractical or unnecessary to expect the
eval(repr(obj)) thing to work.
certainly wouldn't put it like that. __str__ is more about "convert to a
string", and __repr__ is "what the the magic method that gets called by
str(), and __repr__ gets called by repr()
--
Steve
More information about the Tutor
mailing list