Python repr Function With Example | repr vs str in Python

1. Objective – Python repr Function

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

2. 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?

>>> eval(repr(s))

‘Hello’

>>> s

‘Hello’

What about an integer?

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

True

Now, 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.

We recommend you to read Python Method

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.

3. Python repr Example

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

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

“‘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!’”)

‘Hello, world!’

This wouldn’t work:

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

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!)

4. 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)

“‘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)

True

>>> dir(object)

[‘__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

<__main__.Orange object at 0x02C6C1D0>

>>> print(o)

<__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

<__main__.Orange object at 0x02D40E70>

>>> print(o)

I am 7 and orange

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

Python Interview Questions

5. 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))

Hello

>>> print(repr(s))

‘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)

‘3’

>>> repr(3)

‘3’

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

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

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

>>> repr(t)

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

>>> t

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)')

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

Recommended Reading – Python datetime Module

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

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

__repr__ for demo

>>> print(d)

__str__ for demo

>>> str(d)

‘__str__ for demo’

>>> repr(d)

‘__repr__ for demo’

>>> f'{d}'

‘__str__ for demo’

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

6. Conclusion – Python repr

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. 

See also –

Python exec

Reference for Python 

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.