Debugging tools.
- watch(var): print out the name, type, and value of a variable and where in a program this output was requested (used to monitor variables).
- trace(message): print a message and where in the program this message was requested (used to trace the execution).
- dump(obj, hide_underscore=True): print a dump of the object obj (attributes, methods, etc.).
- debugregex(pattern, string): print match, groups, etc. when the regular expression pattern is applied to string.
watch and trace prints information only if the module variable DEBUG has a true value. DEBUG can be initialized from an environment variable PYDEBUG, otherwise it is set to 1 by default. Other modules can monitor their debugging by setting debug.DEBUG = 0 or debug.DEBUG = 1 (note that a single such setting has a “global” effect; it turns off debugging everywhere).
Print out the name, type, and value of a variable and where in a program this output was requested. Used to monitor variables during debugging. As an example, watch(myprm) may lead to this output:
myprm <int> in ./myscript.py(56): myfunction
= 3
The variable is returned to the caller, thus it can be used inside expressions:
myobj.setCallback(lambda self: self.setstate(watch(self.mystate)))
(This function is a modified version of a function taken from the online Python Cookbook:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52314/index_txt
The original code was written by Olivier Dagenais).
Print a message and where in the program this message was requested (as in the function watch). Used to trace the program flow during debugging.
If called from constructors, and sometimes also other class methods with “generic” names, it may be smart to let the message be the classname:
class A:
def __init__(self):
debug.trace(self.__class__.__name__)
def write(self):
debug.trace(self.__class__.__name__)
With frameno=-2 the place where this debug.trace function is called is printed, while smaller values gives printout of previous calls on the call stack. In the previous example, we could look further back to say:
- class A:
- def __init__(self):
- debug.trace(‘Instantiation of ‘+self.__class__.__name__, frameno=-3)
- def write(self):
- debug.trace(‘A.write() call’, frameno=-3)
Setting frameno=-4 may also be useful in some particular cases, for example in a baseclass __init__ which is usually overridden. But there is danger that we then look too far back in the call stack.