In Python, the built-in repr() function returns a string containing a printable representation of an object. For a class object, repr() returns a string enclosed in angle brackets <> containing the name and address of the object by default
This tutorial will go through the syntax of the repr() function and how to use it with code examples.
Table of contents
Python repr() Definition
The name “repr” stands for representation. The repr()
function provides a univocal string representation of an object.
To reconstruct the original object, we can pass the string returned by the repr() function.
Python repr() Syntax
repr(object)
Parameters
object
: The object for which the function returns a printable representation.
Returns
- A string
Example: Passing string object to repr()
Let’s look at an example where we pass a string to the repr()
function:
string = 'researchdatapod' result = repr(string) print(repr(string)) print(eval(repr(string)))
'researchdatapod'
In the above code, we assign the value 'researchdatapod'
to string
. The repr()
function returns 'researchdatapod'
, which is researchdatapod
inside quotes.
If we pass the result from repr()
to eval()
, we will get the original object, which is the case for many types.
print(eval(repr(string)))
researchdatapod
If we create a string representation of researchdatapod
using str()
and pass it to the eval()
method, we will get an error:
string = 'researchdatapod' result = str(string) print(eval(result))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-2-c2a62f2900a2> in <module> 1 string = 'researchdatapod' 2 result = str(string) ----> 3 print(eval(result)) <string> in <module> NameError: name 'researchdatapod' is not defined
Example: Passing tuple object to repr()
Let’s look at an example where we pass a tuple to the repr()
function:
tup = (1, 2, 3, 4, 5) result = repr(tup) print(result) print(type(result))
(1, 2, 3, 4, 5) <class 'str'>
In the above code, we pass a tuple of five integers to the repr()
function. The function returns a string representing the tuple. If we pass the result to the eval()
method, we will get the original object:
obj = eval(result) print(obj) print(type(obj))
(1, 2, 3, 4, 5) <class 'tuple'>
Example: Python repr() method and Class
Let’s look at an example where we call pass an object of a class to the repr()
function. The class has an __init__
method which sets the name attribute.
class Scientist: def __init__(self, name): self.name = name scientist_x = Scientist('Einstein') print(repr(scientist_x))
For a class object, repr()
returns a string enclosed in angle brackets <>
containing the name and address of the object by default. Let’s run the code to see the result:
<__main__.Scientist object at 0x7fde094abd30>
Internally, the repr()
function invokes the built-in __repr__()
method of the given object. We can override the __repr__()
method to obtain a different return value. Let’s look at how to override the __repr__
of the Scientist class:
class Scientist: def __init__(self, name): self.name = name def __repr__(self): return self.name scientist_x = Scientist('Einstein') scientist_y = Scientist('Feynman') print(repr(scientist_x)) print(repr(scientist_y))
In the above code, we override the __repr__()
to return the name attribute of the object. We can set the name attribute when we create an object of the Scientist class. Let’s run the code to see the result:
Einstein Feynman
What is the Difference Between repr() and str()
Both str()
and repr()
create a string object. The str()
method returns a non-canonical string object from the provided object. The repr()
method returns the canonical string representation of the object. We can think of str() as providing the informal, readable string representation of an object whereas repr()
returns the formal string representation of an object.
We use str()
for creating output for the end-user while we use repr()
for debugging and development. The goal of repr is to be univocal and the goal of str
is to be readable.
Let’s look at an example comparing the two methods:
import datetime now = datetime.datetime.now() string_result = str(now) repr_result = repr(now) print(string_result) print(repr_result)
2022-03-29 09:16:01.221422 datetime.datetime(2022, 3, 29, 9, 16, 1, 221422)
str()
displays the date in an understandable fashion for the end-user. repr()
prints the official representation of the datetime object now
. Where official means we can reconstruct the object from the string representation. We use the eval() method to reconstruct the datetime object from the string. Let’s look at how to implement the eval method:
print(type(repr_result)) obj = eval(repr_result) print(obj) print(type(obj))
<class 'str'> 2022-03-29 09:16:01.221422 <class 'datetime.datetime'>
Table of repr() and str() features
The table below summarises the key features of repr() and str().
repr() | str() |
---|---|
Univocal and official | Informal |
Debugging and development | End-user readability |
Can pass to eval() | Passing to eval() raises an error |
Invokes __repr__() | Invokes __str__() |
When to Use Python repr() function?
The repr() function returns the official and univocal representation of an object making repr()
helpful for debugging.
- Working with the
eval()
method - Working with text-based data files like .csv
- When we want to extract flat data from a file
Summary
Congratulations on reading to the end of this tutorial! We have gone through what the repr() function is, how and when to use it and the difference between str()
and repr()
.
To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.