How do you debug in Python? Coming from a Matlab and R user. I'm already aware of pdb.

David Raymond David.Raymond at tomtom.com
Wed Jan 27 10:08:31 EST 2021


In regards to the various comments about adding in print() calls what I've found myself doing is to basically always use the logging module, and use logging.debug() for those.

Somewhere at the top of the script I'll have a line like...

DEBUG = False

...and when initializing the handler to stdout I'll do something like this...

toScreen = logging.StreamHandler(sys.stdout)
toScreen.setLevel(logging.DEBUG if DEBUG else logging.INFO)


That way I can sprinkle in

logging.debug("Some message here")

in various spots. If things are going wrong I can change DEBUG to True to see them on screen, and when I've fixed it I can just set DEBUG back to False. That way I don't have to try finding all those print() statements that were only there for debugging and comment them out or remove them.

As a bonus, if you also set a file logger for example with its level set to logging.DEBUG, then you can have those go into the log file without them cluttering the screen output.

As a side effect to using logging I found I also like having the timestamp automatically prepended to my output by the logger. I'd find myself checking in on something I left running in the background and thinking it's been on that step for "a while", but I have no idea how long "a while" really is. So the timestamps help quickly show "been stuck there for 3 hours" vs "just got to that step 3 seconds before I switched to its window"

I don't claim these are the best practices :) But figured I'd offer another take on it.


More information about the Python-list mailing list