May 7, 2018

Use of __repr__ in python


Problem Statement


How many times you are in the process of debugging/ printing/logging your python objects for a critical issue analysis, and you find output which is very obscure??? Quiet Often?


<__main__.Point instance at 0x7f23e62995f0>

Actual Reason

Consider a 'Point' class which takes in two co-ordinates. Now, when you print the object details, python interpreter understands it as a command to provide the instance details of the object along with its associated class.


class Point:
    def __init__(self, x_cord, y_cord):
        self.x = x_cord
        self.y = y_cord



if __name__ == "__main__":
    d = Point(3,4)
    print d

So, when you run a simple code provided above, you will see that the output is very complicate details of the class object - which provides very little information.


<__main__.Point instance at 0x7f23e62995f0>

For some, this might be sufficient. However, for many of us, we need to understand more about the object than just the plain instance details associated with the class.

Workaround

Python has provided a beautiful mechanism to have a workaround with this. Here we use a built-in class member called __repr__.

Now, consider the below modified version of the same class definition.


class Point:
    def __init__(self, x_cord, y_cord):
        self.x = x_cord
        self.y = y_cord

    def __repr__(self):
        return 'Point in co-ordindate form where x = %s, y = %s' % (self.x,self.y)



if __name__ == "__main__":
    d = Point(3,4)
    print d

when you run the above program, the out changes to the text description as shown below



lvtb9:~/workspace/blog_examples/repr_usage$ python class_repr_usage.py
Point in co-ordindate form where x = 3, y = 4

Wonderful!!!

Conclusion

We might think that these minor tweaks carry little value in overall day-day product development/maintainance.

However, think again - let's say you need to log the object details when an exception is thrown for a code which is legacy and difficult to change. Now just by extending the details of the '__repr__' in your legacy code, you will be easily able to extend the logging details and equip yourself for effective debugging.



No comments:

Post a Comment