Python __str__() and __repr__() functions

Filed Under: Python

We will look into two important python object functions that are very helpful in debugging python code by logging useful information regarding the object.

Python __str__()

This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.

This method must return the String object. If we don’t implement __str__() function for a class, then built-in object implementation is used that actually calls __repr__() function.

Python __repr__()

Python __repr__() function returns the object representation. It could be any valid python expression such as tuple, dictionary, string etc.

This method is called when repr() function is invoked on the object, in that case, __repr__() function must return a String otherwise error will be thrown.

Python __str__ and __repr__ example

Both of these functions are used in debugging, let’s see what happens if we don’t define these functions for an object.


class Person:
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

p = Person('Pankaj', 34)

print(p.__str__())
print(p.__repr__())

Output:


<__main__.Person object at 0x10ff22470>
<__main__.Person object at 0x10ff22470>

As you can see that the default implementation is useless. Let’s go ahead and implement both of these methods.


class Person:
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

    def __repr__(self):
        return {'name':self.name, 'age':self.age}

    def __str__(self):
        return 'Person(name='+self.name+', age='+str(self.age)+ ')'

Notice that we are returning dict for __repr__ function. Let’s see what happens if we use these methods.


p = Person('Pankaj', 34)

# __str__() example
print(p)
print(p.__str__())

s = str(p)
print(s)

# __repr__() example
print(p.__repr__())
print(type(p.__repr__()))
print(repr(p))

Output:


Person(name=Pankaj, age=34)
Person(name=Pankaj, age=34)
Person(name=Pankaj, age=34)
{'name': 'Pankaj', 'age': 34}
<class 'dict'>
  File "/Users/pankaj/Documents/PycharmProjects/BasicPython/basic_examples/str_repr_functions.py", line 29, in <module>
    print(repr(p))
TypeError: __repr__ returned non-string (type dict)

Notice that repr() function is throwing TypeError since our __repr__ implementation is returning dict and not string.

Let’s change the implementation of __repr__ function as follows:


    def __repr__(self):
        return '{name:'+self.name+', age:'+str(self.age)+ '}'

Now it’s returning String, and the new output for object representation calls will be:


{name:Pankaj, age:34}
<class 'str'>
{name:Pankaj, age:34}

Earlier we mentioned that if we don’t implement __str__ function then the __repr__ function is called. Just comment the __str__ function implementation from Person class and print(p) will print {name:Pankaj, age:34}.

Difference between __str__ and __repr__ functions

  1. __str__ must return string object whereas __repr__ can return any python expression.
  2. If __str__ implementation is missing then __repr__ function is used as fallback. There is no fallback if __repr__ function implementation is missing.
  3. If __repr__ function is returning String representation of the object, we can skip implementation of __str__ function.

Summary

Both __str__ and __repr__ functions are very similar. We can get the object representation in String format as well as other specific formats such as tuple and dict to get information about the object.

You can checkout complete python script and more Python examples from our GitHub Repository.

Comments

  1. Laeeq Khan says:

    Very useful. Thanks.

  2. vikas shrivastava says:

    This is really helpful article for me…

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages