What is the difference between __str__ and __repr__ in Python?
(2020 entry)
Q: What's the difference between __str__() and __repr__()?
LONG
This question has been around a long time, and there are a variety of answers of which most are correct (not to mention from several Python community legends[!]). However when it comes down to the nitty-gritty, this question is analogous to asking the difference between the str() and repr() built-in functions. I'm going to describe the differences in my own words (which means I may be "borrowing" liberally from Core Python Programming so pls forgive me).
Both str() and repr() have the same basic job: their goal is to return a string representation of a Python object. What kind of string representation is what differentiates them.
str() & __str__() return a printable string representation of
an object... something human-readable/for human consumptionrepr() & __repr__() return a string representation of an object that is a valid Python expression, an object you can pass to eval() or type into the Python shell without getting an error.For example, let's assign a string to x and an int to y, and simply showing human-readable string versions of each:
>>> x, y = 'foo', 123
>>> str(x), str(y)
('foo', '123')
Can we take what is inside the quotes in both cases and enter them verbatim into the Python interpreter? Let's give it a try:
>>> 123
123
>>> foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
Clearly you can for an int but not necessarily for a str. Similarly, while I can pass '123' to eval(), that doesn't work for 'foo':
>>> eval('123')
123
>>> eval('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
So this tells you the Python shell just eval()s what you give it. Got it? Now, let's repr() both expressions and see what we get. More specifically, take its output and dump those out in the interpreter (there's a point to this which we'll address afterwards):
>>> repr(x), repr(y)
("'foo'", '123')
>>> 123
123
>>> 'foo'
'foo'
Wow, they both work? That's because 'foo', while a printable string representation of that string, it's not evaluatable, but "'foo'" is. 123 is a valid Python int called by either str() or repr(). What happens when we call eval() with these?
>>> eval('123')
123
>>> eval("'foo'")
'foo'
It works because 123 and 'foo' are valid Python objects. Another key takeaway is that while sometimes both return the same thing (the same string representation), that's not always the case. (And yes, yes, I can go create a variable foo where the eval() works, but that's not the point.)
More factoids about both pairs
str() and repr() are called implicitly, meaning they're called on behalf of users: when users execute print (Py1/Py2) or call print() (Py3+), even if users don't call str() explicitly, such a call is made on their behalf before the object is displayed.>>> prompt and press RETURN, the interpreter displays the results of repr() implicitly called on that object.str() and repr() to __str__() and __repr__(), realize that calls to the built-in functions, i.e., str(x) or repr(y) result in calling their object's corresponding special methods: x.__str__() or y.__repr()____str__() and __repr__() for your Python classes, you overload the built-in functions (str() and repr()), allowing instances of your classes to be passed in to str() and repr(). When such calls are made, they turn around and call the class' __str__() and __repr__() (per #3).You can get some insight from this code:
class Foo():
def __repr__(self):
return("repr")
def __str__(self):
return("str")
foo = Foo()
foo #repr
print(foo) #str
__str__ can be invoked on an object by calling str(obj) and should return a human readable string.
__repr__ can be invoked on an object by calling repr(obj) and should return internal object (object fields/attributes)
This example may help:
class C1:pass
class C2:
def __str__(self):
return str(f"{self.__class__.__name__} class str ")
class C3:
def __repr__(self):
return str(f"{self.__class__.__name__} class repr")
class C4:
def __str__(self):
return str(f"{self.__class__.__name__} class str ")
def __repr__(self):
return str(f"{self.__class__.__name__} class repr")
ci1 = C1()
ci2 = C2()
ci3 = C3()
ci4 = C4()
print(ci1) #<__main__.C1 object at 0x0000024C44A80C18>
print(str(ci1)) #<__main__.C1 object at 0x0000024C44A80C18>
print(repr(ci1)) #<__main__.C1 object at 0x0000024C44A80C18>
print(ci2) #C2 class str
print(str(ci2)) #C2 class str
print(repr(ci2)) #<__main__.C2 object at 0x0000024C44AE12E8>
print(ci3) #C3 class repr
print(str(ci3)) #C3 class repr
print(repr(ci3)) #C3 class repr
print(ci4) #C4 class str
print(str(ci4)) #C4 class str
print(repr(ci4)) #C4 class repr
__str__ must return string object whereas __repr__ can return any python expression.__str__ implementation is missing then __repr__ function is used as fallback. There is no fallback if __repr__ function implementation is missing.__repr__ function is returning String representation of the object, we can skip implementation of __str__ function.Source: https://www.journaldev.com/22460/python-str-repr-functions
__repr__ is used everywhere, except by print and str methods (when a __str__is defined !)
Every object inherits __repr__ from the base class that all objects created.
class Person:
pass
p=Person()
if you call repr(p) you will get this as default:
<__main__.Person object at 0x7fb2604f03a0>
But if you call str(p) you will get the same output. it is because when __str__ does not exist, Python calls __repr__
Let's implement our own __str__
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def __repr__(self):
print("__repr__ called")
return f"Person(name='{self.name}',age={self.age})"
p=Person("ali",20)
print(p) and str(p)will return
__repr__ called
Person(name='ali',age=20)
let's add __str__()
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
print('__repr__ called')
return f"Person(name='{self.name}, age=self.age')"
def __str__(self):
print('__str__ called')
return self.name
p=Person("ali",20)
if we call print(p) and str(p), it will call __str__() so it will return
__str__ called
ali
repr(p) will return
repr called "Person(name='ali, age=self.age')"
Let's omit __repr__ and just implement __str__.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
print('__str__ called')
return self.name
p=Person('ali',20)
print(p) will look for the __str__ and will return:
__str__ called
ali
NOTE= if we had __repr__ and __str__ defined, f'name is {p}' would call __str__
Programmers with prior experience in languages with a
toStringmethod tend to implement__str__and not__repr__. If you only implement one of these special methods in Python, choose__repr__.
From Fluent Python book, by Ramalho, Luciano.
Basically __str__ or str() is used for creating output that is human-readable are must be for end-users.
On the other hand, repr() or __repr__ mainly returns canonical string representation of objects which serve the purpose of debugging and development helps the programmers.