In a module I'm writing I have (for the development and testing phases) lots of Print["Messages"]
. I have two questions:
I like to always keep global variables prefixed with the $
, and functions without the prefix, so I'd write:
debugPrint[args___] := $debugPrintFunction[args]
$debugPrintFunction = Print[##] &
Then you can just use debugPrint
exactly like you'd use Print
now. When you want to get rid of the debugging messages, you just unset the variable:
$debugPrintFunction = .
There are some advantages to doing it this way. One is that you can use Block
to switch the debugging on and off locally:
In[1]:= foo[x_] := (debugPrint[x]; x+1)
In[2]:= foo[3]
3
Out[2]= 4
In[3]:= Block[{$debugPrintFunction}, foo[3]
Out[3]= 4
You can even locally make $debugPrintFunction
do something else, like Sow
values for a Reap
to pick up, or direct the debugging messages somewhere else, like
strm = OpenWrite["your/log/path/here", InputForm];
Block[{$debugPrintFunction = Write[strm, ##]},
foo[3]];
Close[strm];
Used judiciously, the dynamic scoping provided by Block
allows the use of global variables in a relatively safe and controlled way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With