I'm trying to write a function that helps me with debugging. Instead of inserting several print statements every now and then, I'd like to insert a one-liner debug statement. And what I'd expect to accomplish is that such function can be reused: I'd like to use it in several functions, in order to print different sets of variables.
In particular what I want to do is this:
def _debugFunction(var_list):
global debug_flag
if debug_flag:
print 'START DEBUGGING:'
< magic code >
print 'END DEBUGGING'
def foo_function(n):
x = 1
y = 2
z = 'string'
debugFunction([x, y, z])
return x + y
So that when I set debug_flag = True
and call foo, the output is:
START DEBUGGING:
x = 1
y = 2
z = 'string'
END DEBUGGING
3
And then, if I set debug_flag = False
and call foo, the output is:
3
In order to do that, I need to get, on runtime, the names of the variables I'm passing to debugFunction()
as arguments, and print it along with their values.
I've searched through other posts and unable to find a direct answer.
How to get a variable name as a string in Python?
retrieving a variable's name in python at runtime?
From what I can actually understand, people are told to use the logging module. I've looked at it and tried to implement as much as a tiny piece of it, but I'm unable to log anything yet (will not surrender, though).
I've also read that people get pointed to __dict()__
, vars()
, or dir()
, but just can't understand how to use them. Moreover: if I try to apply them to my variables I only get errors, or meaningless (to me ;) outputs.
Is there a way to do this? Is this TOO bad practice? If that's the case: what would be good practice?
PS: Perhaps there's no point in wasting efforts trying to implement this, but rather spend that time understanding how to properly use the logging module.