Python repr Function With Example | repr vs str in Python

Python course with 57 real-time projects - Learn Python

Talking of built-in functions in Python, let’s take one more. Today, we will talk about Python repr, concluding with some examples to drive the point home.

Also, we will discuss Python str vs repr. Moreover, we will see working with class objects. 

So, let’s start the Python repr Function. Hope you like our explanation.

Python repr Function With Example

Python repr Function With Example

What is repr() in Python?

Let’s ask the IDLE.

Python repr

What is Python repr Function

This tells us five things:

  • This is a built-in function
  • This takes an object
  • This returns the canonical string representation of this object
  • It has the following syntax:

repr(obj, /)

  • It is true for many object types and most builtins that eval(repr(obj))=obj

Now, what does this last statement mean?

>>> s='Hello'
>>> eval(repr(s))

Output

‘Hello’
>>> s

Output

‘Hello’What about an integer?

>>> x=7
>>> eval(repr(x))==x

TrueNow, according to the official documentation by Python, repr() returns a string that holds a printable representation of an object.

For most types in Python, this will give you a string that yields an object with the same value as when we pass it to eval(). For a few other types, it returns a string delimited in angle brackets.

This holds the type of object and other information like the name and address of that object.

To us, this is the repr() function. To Python, this is a class that controls what it returns for its instances via the __repr__() magic method.

Python repr Example

Let’s get to an example of Python repr function.

>>> msg='Hello, world!'
>>> repr(msg)

Output

“‘Hello, world!’”

A closer look at this tells us this returns ‘Hello, world!’ within double quotes. If we pass this back to eval, it gives us:

>>> eval("'Hello, world!'")

Output

‘Hello, world!’

This wouldn’t work:

>>> eval('Hello, world!')

Output

Traceback (most recent call last):File “<pyshell#16>”, line 1, in <module>

eval(‘Hello, world!’)

File “<string>”, line 1

Hello, world!

^

SyntaxError: unexpected EOF while parsing

This is because we don’t have a variable with that name (Hello, world!)

Working With Class Objects

We said repr() internally makes a call to the __repr__() method. Let’s try this with one of our own classes.

>>> class Color:
       color='orange'
       def __repr__(self):
              return repr(self.color)
>>> o=Color()
>>> repr(o)

Output

“‘orange'”

Here, we override the __repr__() method to get it to do what we want. When we say the word override, note that Color already has an __repr__() method. This is because it inherits from the object class, and object has an __repr__() method.

>>> issubclass(Color,object)

Output

True

>>> dir(object)

Output

[‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’]

Remember when in the beginning, we said repr returns a string in angle brackets for some types? Let’s see how and where.

>>> class Orange:
       def __init__(self,color,size):
               self.color=color
               self.size=size
>>> o=Orange('orange',7)
>>> o

Output

<__main__.Orange object at 0x02C6C1D0>

>>> print(o)

Output

<__main__.Orange object at 0x02C6C1D0>

These are strings with the class name and the id of the object instance(its memory address in CPython). To print this better, we make use of the information that the print() function makes a call to the __str__ dunder/ method:

>>> class Orange:
	def __init__(self,color,size):
                self.color=color
                self.size=size
	def __str__(self):
                return f'I am {self.size} and {self.color}'
>>> o=Orange('orange',7)
>>> o

Output

<__main__.Orange object at 0x02D40E70>

>>> print(o)

Output

I am 7 and orange

That was pretty cool! In Java, we would use the toString() method for this.

str() vs repr() in Python

The __str__() and __repr__() methods both give us strings in return. So what sets them apart?

  • The goal of __repr__ is to be unambiguous and that of __str__ is to be readable.
  • __repr__ is kind of official and __str__ is somewhat informal.

Take an example to ensure you understand the difference:

>>> s='Hello'
>>> print(str(s))

Output

Hello

>>> print(repr(s))

Output

‘Hello’

  • The print statement and str() function make a call to __str__, but repr() makes on to __repr__.
  • Any string at the interpreter prompt makes a call to __str__(), but an object at the prompt makes a call to __repr__().

Want to do prepration for Python Interview Click Here >>>

Take a look:

>>> str(3)

Output

‘3’

>>> repr(3)

Output

‘3’

They appear the same. Okay, now take a look at this one:

>>> import datetime
>>> t=datetime.datetime.now()
>>> str(t) #Readable

Output

‘2018-09-07 17:33:24.261778’

>>> repr(t)

Output

‘datetime.datetime(2018, 9, 7, 17, 33, 24, 261778)’

>>> t

Output

datetime.datetime(2018, 9, 7, 17, 33, 24, 261778)

Using this ‘official’ representation, we can reconstruct the object, but not with what str() gives us:

>>> eval('datetime.datetime(2018, 9, 7, 17, 33, 24, 261778)')

Output

datetime.datetime(2018, 9, 7, 17, 33, 24, 261778)

>>> eval('2018-09-07 17:33:24.261778')

Output

Traceback (most recent call last):File “<pyshell#56>”, line 1, in <module>

eval(‘2018-09-07 17:33:24.261778’)

File “<string>”, line 1

2018-09-07 17:33:24.261778

^

SyntaxError: invalid token

Let’s take another example.

>>> class demo:
       def __init__(self,a,b):
              self.a=a
              self.b=b
       def __repr__(self):
              return '__repr__ for demo'
       def __str__(self):
              return '__str__ for demo'
>>> d=demo(3,4)
>>> d

Output

__repr__ for demo

>>> print(d)

Output

__str__ for demo

>>> str(d)

Output

‘__str__ for demo’

>>> repr(d)

Output

‘__repr__ for demo’

>>> f'{d}'

Output

‘__str__ for demo’

So, this was all in Python repr tutorial. Hope you like our explanation.

Python Interview Questions on repr Functions

  1. What is repr function in Python?
  2. What is the difference between repr and str in Python?
  3. What does repr stand for in Python?
  4. What is the use of repr function in Python?
  5. Give an example of Python repr function.

Conclusion 

The interactive interpreter uses repr() too in giving you the output of your expression:

result=expr; if result is not None: print repr(result)

Hence, in this Python repr tutorial, we discussed the meaning of repr in Python. Also, we looked Python repr example and working with class objects. Moreover, we saw str vs repr in Python.

Still, if you have any query regarding Python repr tutorial, ask in the comment tab. 

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

follow dataflair on YouTube

2 Responses

  1. Diego Bejar says:

    Although the explanation is quite well understood by the final conclusion, however the topic comes in abruptly, because it talks about classes, objects, methods when those topics have not yet been touched, if I would not have knowledge of OOP, it would have been very difficult to understand. Also thank you and I hope you can continue to improve your wonderful blog.

    • DataFlair Team says:

      Python is a language where understanding one topic is essential to comprehend related concepts. Therefore individuals who haven’t studied Python, it might be challenging to grasp, but we’ll put in extra effort to make our content more easily understandable. Your feedback is extremely valuable to us. Thanks for the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *