Quantcast
Channel: Supreme Debugging
Viewing all articles
Browse latest Browse all 13

Use of __repr__ in python

$
0
0

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

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.


classPoint:def__init__(self,x_cord,y_cord):self.x=x_cordself.y=y_cordif__name__=="__main__":d=Point(3,4)printd

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

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.


classPoint:def__init__(self,x_cord,y_cord):self.x=x_cordself.y=y_corddef__repr__(self):return'Point in co-ordindate form where x = %s, y = %s'%(self.x,self.y)if__name__=="__main__":d=Point(3,4)printd

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



lvtb9:~/workspace/blog_examples/repr_usage$pythonclass_repr_usage.pyPointinco-ordindateformwherex=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.




Viewing all articles
Browse latest Browse all 13

Trending Articles