in c code I frequently use printf debugging macros like
#define DPRINT_INT(i) fprintf(stderr,"%s has the value %i at line %i", #i,i, __LINE__)
and then i can do things like DPRINT_INT(height) where it will print the variable or things like DPRINT_INT(from_cm_to_inch(get_average(heights))) and it will print out the whole expression for the name.
To do this for python, since python doesn't have c-like macros
I pass a string and use inspect to get the calling functions environment to call eval with. But I don't like passing strings, its ugly and easy to forget(I have it check type and call an exception if it gets passed a non string) and doesn't work as well with the ide.
There isn't any way to extract the variable names and expressions from the python code for the debug function? is there?
In Python we tend to write modules that we can unittest and / or import into the REPL and drive them there if necessary.
If you can unit-test your functions, you can prove their behaviour for any given input. However, if you must write debug statements, you should use
debug()
from the standardlogging
module.For example:
Will output...
There's a wealth of useful stuff in
inspect
that may help you out in your hour of need.