Question

I'm currently learning Python and to be aware of what's going on behind the scenes I write a lot of printouts. Seeing as it's quite a fuss to go back and comment all the messages I've started writing a module where I set all the messages in the method I want to use them and then use a boolean to turn the messages off and on. Problem is, I get None printouts instead of my debug messages which isn't very elegant. Any way to get around this?

Some sample code:

def setDebug(bool):
    '''
    Toggles the debug messages
    '''

    global _debug
    _debug = bool


def setNewMsg(msg):
    '''
    Appends a new debug message to the list
    '''
    global _debugMsg
    _debugMsg.append(msg)

def getDebugMsg(index):
    '''
    Takes an int for a parameter and returns the debug message needed
    '''
    global _debug
    global _debugMsg

    if _debug == True:
        return _debugMsg[index] 
    else: 
        return
Was it helpful?

Solution

Since you said you're new to Python, I think you should consider using the logging module

Look at this link, also the HOWTO can really help.

from the Python docs:

This module defines functions and classes which implement a flexible event logging system for applications and libraries.

You can set the logging module to save all your prints to file and by controlling the logging level you can control the level of messaged.

Example:

import logging
logging.basicConfig(filename='mylog.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

If level=logging.DEBUG you'll be able to see all messages but by changing to level=logging.INFO it will save to the file only info and above. try the links they are very useful.

OTHER TIPS

You're getting None since you're returning it if your _debug variable is false.

If the _debug is false, you can return an empty string:

return ''

Or you might want to return a message:

return 'Debug mode is not set to True'

Returning nothing is basically the same as returning None. Even if you don't return anything, Python will set the returned value as None:

>>> def test():
    pass

>>> a = test()
>>> print a
None

Also, if you want to use your method instead of the logging module, you might want to check if _debugMsg[index] exists.

if _debug:
    try:
       return _debugMsg[index]
    except IndexError:
       return 'The debug message hasn't listed yet.'

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top