What is the difference between __str__ and __repr__ in Python?(Request Post)
Purpose of __str__ and __repr__ in Python
Before we dive into the discussion, let's check out the official documentation of Python about these two functions:From the official documentation, we know that bothobject.__repr__(self)
: called by therepr()
built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object.
object.__str__(self)
: called by thestr()
build-in function and by the print statement to compute the "informal" string representation of an object.
Quote from Python's Data Model
__repr__
and __str__
are used to "represent" an object. __repr__
should be the "official" representation while __str__
is the "informal" representation.So, what does Python's default
__repr__
and __str__
implementation of any object look like?For example, let's say we have a
int
x
and a str
y
and we want to know the return value of __repr__
and __str__
of these two objects:repr()
and str()
are identical for int x
, you should notice the difference between the return values for str y
. It is important to realize the default implementation of __repr__
for a str
object can be called as an argument to eval
and the return value would be a valid str
object:__str__
is not even a valid statement that can be executed by eval:__repr__
should be unambiguous and contain as much information as possible.__repr__
for ClassB
which causes an infinite recursion problem where a.__repr__
calls b.__repr__
which calls a.__repr__
which calls b.__repr__,
on and on forever, you could define ClassB.__repr__
in a different way. A way that shows as much information about an
object as possible would be just as good as a valid eval-confined __repr__
.__repr__
is the official representation for an object, you always want to call "repr(an_object)"
to get the most comprehensive information about an object. However, sometimes __str__
is useful as well. Because __repr__
could be too complicated to inspect if the object in question is complex (imagine an object with a dozen attributes), __str__
is helpful to serve as a quick overview of complicated objects. For example, suppose you want to inspect a datetime
object in the middle of a lengthy log file to find out why the datetime
of a user's photo is not correct:__str__
representation of now looks cleaner and easier to read than the formal representation generated from __repr__
. Sometimes, being able to quickly grasp what's stored in an object is valuable to grab the "big" picture of a complex program.Gotchas between __str__ and __repr__ in Python
One important catch to keep in mind is that container's__str__
uses contained objects' __repr__
.__str__
call of a tuple calls the contained objects' __repr__
,
the "formal" representation of an object. Although the formal
representation is harder to read than an informal one, it
is unambiguous and more robust against bugs.
Comments
Post a Comment