Brian Kernighan said: Debugging is twice as hard as writing the code in the first place. […] Although this quote in its full glory is a warning to programmers that they can easily outsmart themselves – it still is harder to debug than to write.

I had to fix some Python code recently – and unfortunately my fixing had to start with adding proper debugging routines to existing classes.

It is extremely difficult to read and understand debugging messages if there is no timestamp information attached to them – and that was the case of the code I had to fix. The moment you add plenty of debugging calls the output may quickly become bloated and you are going to lose the clear overview in terms of “where was that method invoked” – so it is a smart choice to include also the line number.

In Python this can be achieved in the following way:

#!/usr/bin/python
 
import inspect
import datetime
 
class myclass:
    def __init__(self):
	pass
 
    def debug(self,data):
	print "%s at line %d = %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), inspect.currentframe().f_back.f_lineno, data)
 
mc = myclass()
 
print "Hello!"
mc.debug("Testing")
print "---" 
print "- some lines -"
mc.debug("A bit lower in the code")

A nice and clean solution – date and line. Of course this is just a basic function – depending on your needs it can be expanded, but the “must have” things are there: timestamp, line and of course the text.

The output looks as follows:

Hello!
2013-08-19 23:00:36 at line 19 => Testing
---
- some lines -
2013-08-19 23:00:36 at line 22 => A bit lower in the code

Happy and effective debugging!