Search code examples
python

Using print statements only to debug


I have been coding a lot in Python of late. And I have been working with data that I haven't worked with before, using formulae never seen before and dealing with huge files. All this made me write a lot of print statements to verify if it's all going right and identify the points of failure. But, generally, outputting so much information is not a good practice. How do I use the print statements only when I want to debug and let them be skipped when I don't want them to be printed?


Solution

  • The logging module in the standard library has everything you could want. It may seem excessive at first, but only use the parts you need. I'd recommend using logging.basicConfig to set the logging level then using the simple log methods: debug, info, warning, error and critical.

    import logging
    logging.basicConfig(level=logging.DEBUG)
    logging.debug('A debug message!')
    logging.info('We processed %d records', len(processed_records))